blob: d69121c7538d6037ed685eb04d129dd07be34ea1 [file] [log] [blame]
Mark Beierl821bfc92023-01-24 21:15:25 -05001#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3
4##
Mark Beierl821bfc92023-01-24 21:15:25 -05005#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License. You may obtain
8# a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15# License for the specific language governing permissions and limitations
16# under the License.
17##
18
Mark Beierl821bfc92023-01-24 21:15:25 -050019import asyncio
20import getopt
21import logging
22import logging.handlers
Mark Beierl2bed6072023-04-05 20:01:41 +000023import os
Mark Beierl821bfc92023-01-24 21:15:25 -050024import sys
25import yaml
26
Mark Beierl821bfc92023-01-24 21:15:25 -050027from osm_common.dbbase import DbException
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000028from osm_common.temporal_constants import LCM_TASK_QUEUE
Mark Beierl821bfc92023-01-24 21:15:25 -050029from osm_lcm.data_utils.database.database import Database
30from osm_lcm.data_utils.lcm_config import LcmCfg
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000031from osm_lcm.lcm_utils import LcmException
Mark Beierl821bfc92023-01-24 21:15:25 -050032from os import path
Mark Beierl2bed6072023-04-05 20:01:41 +000033from osm_lcm.temporal.lcm_activities import NsLcmActivity
34from osm_lcm.temporal.lcm_workflows import NsNoOpWorkflow
Mark Beierl0c202d22023-04-06 13:58:31 +000035from osm_lcm.temporal.vim_activities import VimDbActivity
36from osm_lcm.temporal.juju_paas_activities import JujuPaasConnector
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000037from osm_lcm.temporal.vim_workflows import (
38 VimCreateWorkflow,
39 VimDeleteWorkflow,
40 VimUpdateWorkflow,
41)
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +000042from osm_lcm.temporal.vdu_workflows import VduInstantiateWorkflow
Mark Beierl821bfc92023-01-24 21:15:25 -050043from temporalio.client import Client
44from temporalio.worker import Worker
45
46
47class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050048 main_config = LcmCfg()
49
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000050 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050051 """
52 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000053 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050054 :return: None
55 """
56 self.db = None
Mark Beierl821bfc92023-01-24 21:15:25 -050057 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000058 self._load_configuration(config_file)
59 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050060
61 try:
62 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050063 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050064 self.logger.critical(str(e), exc_info=True)
65 raise LcmException(str(e))
66
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000067 def _load_configuration(self, config_file):
68 config = self._read_config_file(config_file)
69 self.main_config.set_from_dict(config)
70 self.main_config.transform()
71 self.main_config.load_from_env()
72 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
73
74 def _read_config_file(self, config_file):
75 try:
76 with open(config_file) as f:
77 return yaml.safe_load(f)
78 except Exception as e:
79 self.logger.critical("At config file '{}': {}".format(config_file, e))
80 exit(1)
81
82 @staticmethod
83 def _get_log_formatter_simple():
84 log_format_simple = (
85 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
86 )
87 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
88
89 def _create_file_handler(self):
90 return logging.handlers.RotatingFileHandler(
91 self.main_config.globalConfig.logfile,
92 maxBytes=100e6,
93 backupCount=9,
94 delay=0,
95 )
96
97 def _log_other_modules(self):
98 for logger in ("message", "database", "storage", "tsdb", "temporal"):
99 logger_config = self.main_config.to_dict()[logger]
100 logger_module = logging.getLogger(logger_config["logger_name"])
101 if logger_config["logfile"]:
102 file_handler = logging.handlers.RotatingFileHandler(
103 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
104 )
105 file_handler.setFormatter(self._get_log_formatter_simple())
106 logger_module.addHandler(file_handler)
107 if logger_config["loglevel"]:
108 logger_module.setLevel(logger_config["loglevel"])
109
110 def _configure_logging(self):
111 if self.main_config.globalConfig.logfile:
112 file_handler = self._create_file_handler()
113 file_handler.setFormatter(self._get_log_formatter_simple())
114 self.logger.addHandler(file_handler)
115
116 if not self.main_config.globalConfig.to_dict()["nologging"]:
117 str_handler = logging.StreamHandler()
118 str_handler.setFormatter(self._get_log_formatter_simple())
119 self.logger.addHandler(str_handler)
120
121 if self.main_config.globalConfig.to_dict()["loglevel"]:
122 self.logger.setLevel(self.main_config.globalConfig.loglevel)
123
124 self._log_other_modules()
125 self.logger.critical("starting osm/nglcm")
126
Mark Beierl821bfc92023-01-24 21:15:25 -0500127 async def start(self):
Mark Beierl821bfc92023-01-24 21:15:25 -0500128 temporal_api = (
129 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
130 )
Mark Beierl821bfc92023-01-24 21:15:25 -0500131 client = await Client.connect(temporal_api)
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000132 vim_data_activity_instance = VimDbActivity(self.db)
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000133 paas_connector_instance = JujuPaasConnector(self.db)
Mark Beierl2bed6072023-04-05 20:01:41 +0000134 nslcm_activity_instance = NsLcmActivity(self.db)
Mark Beierl821bfc92023-01-24 21:15:25 -0500135
Mark Beierl2bed6072023-04-05 20:01:41 +0000136 workflows = [
137 NsNoOpWorkflow,
138 VimCreateWorkflow,
139 VimDeleteWorkflow,
140 VimUpdateWorkflow,
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000141 VduInstantiateWorkflow,
Mark Beierl2bed6072023-04-05 20:01:41 +0000142 ]
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000143 activities = [
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000144 vim_data_activity_instance.update_vim_operation_state,
145 vim_data_activity_instance.update_vim_state,
146 vim_data_activity_instance.delete_vim_record,
Mark Beierl2bed6072023-04-05 20:01:41 +0000147 nslcm_activity_instance.update_ns_lcm_operation_state,
148 nslcm_activity_instance.no_op,
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000149 paas_connector_instance.test_vim_connectivity,
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000150 paas_connector_instance.create_model_if_doesnt_exist,
151 paas_connector_instance.deploy_charm,
152 paas_connector_instance.check_charm_status,
Mark Beierl821bfc92023-01-24 21:15:25 -0500153 ]
Mark Beierl821bfc92023-01-24 21:15:25 -0500154
Mark Beierl2bed6072023-04-05 20:01:41 +0000155 # Check if we are running under a debugger
156 debug = os.getenv("VSCODE_IPC_HOOK_CLI") is not None
157
Mark Beierl821bfc92023-01-24 21:15:25 -0500158 worker = Worker(
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000159 client,
160 task_queue=LCM_TASK_QUEUE,
161 workflows=workflows,
162 activities=activities,
Mark Beierl2bed6072023-04-05 20:01:41 +0000163 debug_mode=debug,
Mark Beierl821bfc92023-01-24 21:15:25 -0500164 )
165
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000166 self.logger.info("Starting LCM temporal worker")
Mark Beierl821bfc92023-01-24 21:15:25 -0500167 await worker.run()
168
Mark Beierl821bfc92023-01-24 21:15:25 -0500169
Mark Beierl821bfc92023-01-24 21:15:25 -0500170if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500171 try:
172 opts, args = getopt.getopt(
173 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
174 )
175 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
176 config_file = None
177 for o, a in opts:
178 if o in ("-c", "--config"):
179 config_file = a
180 else:
181 assert False, "Unhandled option"
182
183 if config_file:
184 if not path.isfile(config_file):
185 print(
186 "configuration file '{}' does not exist".format(config_file),
187 file=sys.stderr,
188 )
189 exit(1)
190 else:
191 for config_file in (
192 __file__[: __file__.rfind(".")] + ".cfg",
193 "./lcm.cfg",
194 "/etc/osm/lcm.cfg",
195 ):
196 print(f"{config_file}")
197 if path.isfile(config_file):
198 break
199 else:
200 print(
201 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
202 file=sys.stderr,
203 )
204 exit(1)
205 lcm = NGLcm(config_file)
206 asyncio.run(lcm.start())
207 except (LcmException, getopt.GetoptError) as e:
208 print(str(e), file=sys.stderr)
209 # usage()
210 exit(1)