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
== "heal":
459 # self.logger.debug("Healing NS {}".format(nsr_id))
461 nslcmop_id
= nslcmop
["_id"]
462 nsr_id
= nslcmop
["nsInstanceId"]
463 task
= asyncio
.ensure_future(self
.ns
.heal(nsr_id
, nslcmop_id
))
464 self
.lcm_tasks
.register(
465 "ns", nsr_id
, nslcmop_id
, "ns_heal", task
468 elif command
== "migrate":
470 nslcmop_id
= nslcmop
["_id"]
471 nsr_id
= nslcmop
["nsInstanceId"]
472 task
= asyncio
.ensure_future(self
.ns
.migrate(nsr_id
, nslcmop_id
))
473 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_migrate", task
)
475 elif command
== "show":
478 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
480 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
481 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
484 db_nsr
["operational-status"],
485 db_nsr
["config-status"],
486 db_nsr
["detailed-status"],
487 db_nsr
["_admin"]["deployed"],
488 self
.lcm_ns_tasks
.get(nsr_id
),
491 except Exception as e
:
492 print("nsr {} not found: {}".format(nsr_id
, e
))
495 elif command
== "deleted":
496 return # TODO cleaning of task just in case should be done
507 ): # "scaled-cooldown-time"
510 elif topic
== "nsi": # netslice LCM processes (instantiate, terminate, etc)
511 if command
== "instantiate":
512 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
514 nsilcmop_id
= nsilcmop
["_id"] # slice operation id
515 nsir_id
= nsilcmop
["netsliceInstanceId"] # slice record id
516 task
= asyncio
.ensure_future(
517 self
.netslice
.instantiate(nsir_id
, nsilcmop_id
)
519 self
.lcm_tasks
.register(
520 "nsi", nsir_id
, nsilcmop_id
, "nsi_instantiate", task
523 elif command
== "terminate":
524 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
526 nsilcmop_id
= nsilcmop
["_id"] # slice operation id
527 nsir_id
= nsilcmop
["netsliceInstanceId"] # slice record id
528 self
.lcm_tasks
.cancel(topic
, nsir_id
)
529 task
= asyncio
.ensure_future(
530 self
.netslice
.terminate(nsir_id
, nsilcmop_id
)
532 self
.lcm_tasks
.register(
533 "nsi", nsir_id
, nsilcmop_id
, "nsi_terminate", task
536 elif command
== "show":
539 db_nsir
= self
.db
.get_one("nsirs", {"_id": nsir_id
})
541 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
542 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
545 db_nsir
["operational-status"],
546 db_nsir
["config-status"],
547 db_nsir
["detailed-status"],
548 db_nsir
["_admin"]["deployed"],
549 self
.lcm_netslice_tasks
.get(nsir_id
),
552 except Exception as e
:
553 print("nsir {} not found: {}".format(nsir_id
, e
))
556 elif command
== "deleted":
557 return # TODO cleaning of task just in case should be done
564 ): # "scaled-cooldown-time"
566 elif topic
== "vim_account":
567 vim_id
= params
["_id"]
568 if command
in ("create", "created"):
569 if not self
.config
["ro_config"].get("ng"):
570 task
= asyncio
.ensure_future(self
.vim
.create(params
, order_id
))
571 self
.lcm_tasks
.register(
572 "vim_account", vim_id
, order_id
, "vim_create", task
575 elif command
== "delete" or command
== "deleted":
576 self
.lcm_tasks
.cancel(topic
, vim_id
)
577 task
= asyncio
.ensure_future(self
.vim
.delete(params
, order_id
))
578 self
.lcm_tasks
.register(
579 "vim_account", vim_id
, order_id
, "vim_delete", task
582 elif command
== "show":
583 print("not implemented show with vim_account")
586 elif command
in ("edit", "edited"):
587 if not self
.config
["ro_config"].get("ng"):
588 task
= asyncio
.ensure_future(self
.vim
.edit(params
, order_id
))
589 self
.lcm_tasks
.register(
590 "vim_account", vim_id
, order_id
, "vim_edit", task
593 elif command
== "deleted":
594 return # TODO cleaning of task just in case should be done
595 elif topic
== "wim_account":
596 wim_id
= params
["_id"]
597 if command
in ("create", "created"):
598 if not self
.config
["ro_config"].get("ng"):
599 task
= asyncio
.ensure_future(self
.wim
.create(params
, order_id
))
600 self
.lcm_tasks
.register(
601 "wim_account", wim_id
, order_id
, "wim_create", task
604 elif command
== "delete" or command
== "deleted":
605 self
.lcm_tasks
.cancel(topic
, wim_id
)
606 task
= asyncio
.ensure_future(self
.wim
.delete(params
, order_id
))
607 self
.lcm_tasks
.register(
608 "wim_account", wim_id
, order_id
, "wim_delete", task
611 elif command
== "show":
612 print("not implemented show with wim_account")
615 elif command
in ("edit", "edited"):
616 task
= asyncio
.ensure_future(self
.wim
.edit(params
, order_id
))
617 self
.lcm_tasks
.register(
618 "wim_account", wim_id
, order_id
, "wim_edit", task
621 elif command
== "deleted":
622 return # TODO cleaning of task just in case should be done
624 _sdn_id
= params
["_id"]
625 if command
in ("create", "created"):
626 if not self
.config
["ro_config"].get("ng"):
627 task
= asyncio
.ensure_future(self
.sdn
.create(params
, order_id
))
628 self
.lcm_tasks
.register(
629 "sdn", _sdn_id
, order_id
, "sdn_create", task
632 elif command
== "delete" or command
== "deleted":
633 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
634 task
= asyncio
.ensure_future(self
.sdn
.delete(params
, order_id
))
635 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
637 elif command
in ("edit", "edited"):
638 task
= asyncio
.ensure_future(self
.sdn
.edit(params
, order_id
))
639 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
641 elif command
== "deleted":
642 return # TODO cleaning of task just in case should be done
643 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
645 async def kafka_read(self
):
647 "Task kafka_read Enter with worker_id={}".format(self
.worker_id
)
649 # future = asyncio.Future()
650 self
.consecutive_errors
= 0
651 self
.first_start
= True
652 while self
.consecutive_errors
< 10:
665 topics_admin
= ("admin",)
666 await asyncio
.gather(
668 topics
, self
.loop
, self
.kafka_read_callback
, from_beginning
=True
670 self
.msg_admin
.aioread(
673 self
.kafka_read_callback
,
678 except LcmExceptionExit
:
679 self
.logger
.debug("Bye!")
681 except Exception as e
:
682 # if not first_start is the first time after starting. So leave more time and wait
683 # to allow kafka starts
684 if self
.consecutive_errors
== 8 if not self
.first_start
else 30:
686 "Task kafka_read task exit error too many errors. Exception: {}".format(
691 self
.consecutive_errors
+= 1
693 "Task kafka_read retrying after Exception {}".format(e
)
695 wait_time
= 2 if not self
.first_start
else 5
696 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
698 # self.logger.debug("Task kafka_read terminating")
699 self
.logger
.debug("Task kafka_read exit")
704 self
.loop
.run_until_complete(self
.check_RO_version())
706 self
.ns
= ns
.NsLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
707 self
.netslice
= netslice
.NetsliceLcm(
708 self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
, self
.ns
710 self
.vim
= vim_sdn
.VimLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
711 self
.wim
= vim_sdn
.WimLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
712 self
.sdn
= vim_sdn
.SdnLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
713 self
.k8scluster
= vim_sdn
.K8sClusterLcm(
714 self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
716 self
.vca
= vim_sdn
.VcaLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
717 self
.k8srepo
= vim_sdn
.K8sRepoLcm(
718 self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
721 self
.loop
.run_until_complete(
722 asyncio
.gather(self
.kafka_read(), self
.kafka_ping())
726 # self.logger.debug("Terminating cancelling creation tasks")
727 # self.lcm_tasks.cancel("ALL", "create")
729 # while self.is_pending_tasks():
730 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
731 # await asyncio.sleep(2, loop=self.loop)
734 # self.lcm_tasks.cancel("ALL", "ALL")
738 self
.db
.db_disconnect()
740 self
.msg
.disconnect()
742 self
.msg_admin
.disconnect()
744 self
.fs
.fs_disconnect()
746 def read_config_file(self
, config_file
):
747 # TODO make a [ini] + yaml inside parser
748 # the configparser library is not suitable, because it does not admit comments at the end of line,
749 # and not parse integer or boolean
751 # read file as yaml format
752 with
open(config_file
) as f
:
753 conf
= yaml
.load(f
, Loader
=yaml
.Loader
)
754 # Ensure all sections are not empty
767 # read all environ that starts with OSMLCM_
768 for k
, v
in environ
.items():
769 if not k
.startswith("OSMLCM_"):
771 subject
, _
, item
= k
[7:].lower().partition("_")
774 if subject
in ("ro", "vca"):
775 # put in capital letter
776 subject
= subject
.upper()
778 if item
== "port" or subject
== "timeout":
779 conf
[subject
][item
] = int(v
)
781 conf
[subject
][item
] = v
782 except Exception as e
:
784 "skipping environ '{}' on exception '{}'".format(k
, e
)
787 # backward compatibility of VCA parameters
789 if "pubkey" in conf
["VCA"]:
790 conf
["VCA"]["public_key"] = conf
["VCA"].pop("pubkey")
791 if "cacert" in conf
["VCA"]:
792 conf
["VCA"]["ca_cert"] = conf
["VCA"].pop("cacert")
793 if "apiproxy" in conf
["VCA"]:
794 conf
["VCA"]["api_proxy"] = conf
["VCA"].pop("apiproxy")
796 if "enableosupgrade" in conf
["VCA"]:
797 conf
["VCA"]["enable_os_upgrade"] = conf
["VCA"].pop("enableosupgrade")
798 if isinstance(conf
["VCA"].get("enable_os_upgrade"), str):
799 if conf
["VCA"]["enable_os_upgrade"].lower() == "false":
800 conf
["VCA"]["enable_os_upgrade"] = False
801 elif conf
["VCA"]["enable_os_upgrade"].lower() == "true":
802 conf
["VCA"]["enable_os_upgrade"] = True
804 if "aptmirror" in conf
["VCA"]:
805 conf
["VCA"]["apt_mirror"] = conf
["VCA"].pop("aptmirror")
808 except Exception as e
:
809 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
813 def get_process_id():
815 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
816 will provide a random one
819 # Try getting docker id. If fails, get pid
821 with
open("/proc/self/cgroup", "r") as f
:
822 text_id_
= f
.readline()
823 _
, _
, text_id
= text_id_
.rpartition("/")
824 text_id
= text_id
.replace("\n", "")[:12]
830 return "".join(random_choice("0123456789abcdef") for _
in range(12))
835 """Usage: {} [options]
836 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
837 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
838 -h|--help: shows this help
843 # --log-socket-host HOST: send logs to this host")
844 # --log-socket-port PORT: send logs using this port (default: 9022)")
847 if __name__
== "__main__":
850 # print("SYS.PATH='{}'".format(sys.path))
851 # load parameters and configuration
857 opts
, args
= getopt
.getopt(
858 sys
.argv
[1:], "hc:", ["config=", "help", "health-check"]
860 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
863 if o
in ("-h", "--help"):
866 elif o
in ("-c", "--config"):
868 elif o
== "--health-check":
869 from osm_lcm
.lcm_hc
import health_check
871 health_check(health_check_file
, Lcm
.ping_interval_pace
)
872 # elif o == "--log-socket-port":
873 # log_socket_port = a
874 # elif o == "--log-socket-host":
875 # log_socket_host = a
876 # elif o == "--log-file":
879 assert False, "Unhandled option"
882 if not path
.isfile(config_file
):
884 "configuration file '{}' does not exist".format(config_file
),
890 __file__
[: __file__
.rfind(".")] + ".cfg",
894 if path
.isfile(config_file
):
898 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
902 lcm
= Lcm(config_file
)
904 except (LcmException
, getopt
.GetoptError
) as e
:
905 print(str(e
), file=sys
.stderr
)