blob: 30e4b367a5f7b26e0cb29840097f6953b086026c [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
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000035from osm_lcm.temporal.vim_activities import VimDbActivity, JujuPaasConnector
36from osm_lcm.temporal.vim_workflows import (
37 VimCreateWorkflow,
38 VimDeleteWorkflow,
39 VimUpdateWorkflow,
40)
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +000041from osm_lcm.temporal.vdu_workflows import VduInstantiateWorkflow
Mark Beierl821bfc92023-01-24 21:15:25 -050042from temporalio.client import Client
43from temporalio.worker import Worker
44
45
46class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050047 main_config = LcmCfg()
48
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000049 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050050 """
51 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000052 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050053 :return: None
54 """
55 self.db = None
Mark Beierl821bfc92023-01-24 21:15:25 -050056 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000057 self._load_configuration(config_file)
58 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050059
60 try:
61 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050062 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050063 self.logger.critical(str(e), exc_info=True)
64 raise LcmException(str(e))
65
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000066 def _load_configuration(self, config_file):
67 config = self._read_config_file(config_file)
68 self.main_config.set_from_dict(config)
69 self.main_config.transform()
70 self.main_config.load_from_env()
71 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
72
73 def _read_config_file(self, config_file):
74 try:
75 with open(config_file) as f:
76 return yaml.safe_load(f)
77 except Exception as e:
78 self.logger.critical("At config file '{}': {}".format(config_file, e))
79 exit(1)
80
81 @staticmethod
82 def _get_log_formatter_simple():
83 log_format_simple = (
84 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
85 )
86 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
87
88 def _create_file_handler(self):
89 return logging.handlers.RotatingFileHandler(
90 self.main_config.globalConfig.logfile,
91 maxBytes=100e6,
92 backupCount=9,
93 delay=0,
94 )
95
96 def _log_other_modules(self):
97 for logger in ("message", "database", "storage", "tsdb", "temporal"):
98 logger_config = self.main_config.to_dict()[logger]
99 logger_module = logging.getLogger(logger_config["logger_name"])
100 if logger_config["logfile"]:
101 file_handler = logging.handlers.RotatingFileHandler(
102 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
103 )
104 file_handler.setFormatter(self._get_log_formatter_simple())
105 logger_module.addHandler(file_handler)
106 if logger_config["loglevel"]:
107 logger_module.setLevel(logger_config["loglevel"])
108
109 def _configure_logging(self):
110 if self.main_config.globalConfig.logfile:
111 file_handler = self._create_file_handler()
112 file_handler.setFormatter(self._get_log_formatter_simple())
113 self.logger.addHandler(file_handler)
114
115 if not self.main_config.globalConfig.to_dict()["nologging"]:
116 str_handler = logging.StreamHandler()
117 str_handler.setFormatter(self._get_log_formatter_simple())
118 self.logger.addHandler(str_handler)
119
120 if self.main_config.globalConfig.to_dict()["loglevel"]:
121 self.logger.setLevel(self.main_config.globalConfig.loglevel)
122
123 self._log_other_modules()
124 self.logger.critical("starting osm/nglcm")
125
Mark Beierl821bfc92023-01-24 21:15:25 -0500126 async def start(self):
Mark Beierl821bfc92023-01-24 21:15:25 -0500127 temporal_api = (
128 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
129 )
Mark Beierl821bfc92023-01-24 21:15:25 -0500130 client = await Client.connect(temporal_api)
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000131 vim_data_activity_instance = VimDbActivity(self.db)
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000132 paas_connector_instance = JujuPaasConnector(self.db)
Mark Beierl2bed6072023-04-05 20:01:41 +0000133 nslcm_activity_instance = NsLcmActivity(self.db)
Mark Beierl821bfc92023-01-24 21:15:25 -0500134
Mark Beierl2bed6072023-04-05 20:01:41 +0000135 workflows = [
136 NsNoOpWorkflow,
137 VimCreateWorkflow,
138 VimDeleteWorkflow,
139 VimUpdateWorkflow,
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000140 VduInstantiateWorkflow,
Mark Beierl2bed6072023-04-05 20:01:41 +0000141 ]
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000142 activities = [
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000143 vim_data_activity_instance.update_vim_operation_state,
144 vim_data_activity_instance.update_vim_state,
145 vim_data_activity_instance.delete_vim_record,
Mark Beierl2bed6072023-04-05 20:01:41 +0000146 nslcm_activity_instance.update_ns_lcm_operation_state,
147 nslcm_activity_instance.no_op,
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000148 paas_connector_instance.test_vim_connectivity,
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000149 paas_connector_instance.create_model_if_doesnt_exist,
150 paas_connector_instance.deploy_charm,
151 paas_connector_instance.check_charm_status,
Mark Beierl821bfc92023-01-24 21:15:25 -0500152 ]
Mark Beierl821bfc92023-01-24 21:15:25 -0500153
Mark Beierl2bed6072023-04-05 20:01:41 +0000154 # Check if we are running under a debugger
155 debug = os.getenv("VSCODE_IPC_HOOK_CLI") is not None
156
Mark Beierl821bfc92023-01-24 21:15:25 -0500157 worker = Worker(
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000158 client,
159 task_queue=LCM_TASK_QUEUE,
160 workflows=workflows,
161 activities=activities,
Mark Beierl2bed6072023-04-05 20:01:41 +0000162 debug_mode=debug,
Mark Beierl821bfc92023-01-24 21:15:25 -0500163 )
164
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000165 self.logger.info("Starting LCM temporal worker")
Mark Beierl821bfc92023-01-24 21:15:25 -0500166 await worker.run()
167
Mark Beierl821bfc92023-01-24 21:15:25 -0500168
Mark Beierl821bfc92023-01-24 21:15:25 -0500169if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500170 try:
171 opts, args = getopt.getopt(
172 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
173 )
174 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
175 config_file = None
176 for o, a in opts:
177 if o in ("-c", "--config"):
178 config_file = a
179 else:
180 assert False, "Unhandled option"
181
182 if config_file:
183 if not path.isfile(config_file):
184 print(
185 "configuration file '{}' does not exist".format(config_file),
186 file=sys.stderr,
187 )
188 exit(1)
189 else:
190 for config_file in (
191 __file__[: __file__.rfind(".")] + ".cfg",
192 "./lcm.cfg",
193 "/etc/osm/lcm.cfg",
194 ):
195 print(f"{config_file}")
196 if path.isfile(config_file):
197 break
198 else:
199 print(
200 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
201 file=sys.stderr,
202 )
203 exit(1)
204 lcm = NGLcm(config_file)
205 asyncio.run(lcm.start())
206 except (LcmException, getopt.GetoptError) as e:
207 print(str(e), file=sys.stderr)
208 # usage()
209 exit(1)