blob: 0e8811be57dc08ce1e7fb1ed0b977ee256ac1d54 [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)
Mark Beierl821bfc92023-01-24 21:15:25 -050041from temporalio.client import Client
42from temporalio.worker import Worker
43
44
45class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050046 main_config = LcmCfg()
47
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000048 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050049 """
50 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000051 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050052 :return: None
53 """
54 self.db = None
Mark Beierl821bfc92023-01-24 21:15:25 -050055 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000056 self._load_configuration(config_file)
57 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050058
59 try:
60 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050061 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050062 self.logger.critical(str(e), exc_info=True)
63 raise LcmException(str(e))
64
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000065 def _load_configuration(self, config_file):
66 config = self._read_config_file(config_file)
67 self.main_config.set_from_dict(config)
68 self.main_config.transform()
69 self.main_config.load_from_env()
70 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
71
72 def _read_config_file(self, config_file):
73 try:
74 with open(config_file) as f:
75 return yaml.safe_load(f)
76 except Exception as e:
77 self.logger.critical("At config file '{}': {}".format(config_file, e))
78 exit(1)
79
80 @staticmethod
81 def _get_log_formatter_simple():
82 log_format_simple = (
83 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
84 )
85 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
86
87 def _create_file_handler(self):
88 return logging.handlers.RotatingFileHandler(
89 self.main_config.globalConfig.logfile,
90 maxBytes=100e6,
91 backupCount=9,
92 delay=0,
93 )
94
95 def _log_other_modules(self):
96 for logger in ("message", "database", "storage", "tsdb", "temporal"):
97 logger_config = self.main_config.to_dict()[logger]
98 logger_module = logging.getLogger(logger_config["logger_name"])
99 if logger_config["logfile"]:
100 file_handler = logging.handlers.RotatingFileHandler(
101 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
102 )
103 file_handler.setFormatter(self._get_log_formatter_simple())
104 logger_module.addHandler(file_handler)
105 if logger_config["loglevel"]:
106 logger_module.setLevel(logger_config["loglevel"])
107
108 def _configure_logging(self):
109 if self.main_config.globalConfig.logfile:
110 file_handler = self._create_file_handler()
111 file_handler.setFormatter(self._get_log_formatter_simple())
112 self.logger.addHandler(file_handler)
113
114 if not self.main_config.globalConfig.to_dict()["nologging"]:
115 str_handler = logging.StreamHandler()
116 str_handler.setFormatter(self._get_log_formatter_simple())
117 self.logger.addHandler(str_handler)
118
119 if self.main_config.globalConfig.to_dict()["loglevel"]:
120 self.logger.setLevel(self.main_config.globalConfig.loglevel)
121
122 self._log_other_modules()
123 self.logger.critical("starting osm/nglcm")
124
Mark Beierl821bfc92023-01-24 21:15:25 -0500125 async def start(self):
Mark Beierl821bfc92023-01-24 21:15:25 -0500126 temporal_api = (
127 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
128 )
Mark Beierl821bfc92023-01-24 21:15:25 -0500129 client = await Client.connect(temporal_api)
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000130 data_activity_instance = VimDbActivity(self.db)
131 paas_connector_instance = JujuPaasConnector(self.db)
Mark Beierl2bed6072023-04-05 20:01:41 +0000132 nslcm_activity_instance = NsLcmActivity(self.db)
Mark Beierl821bfc92023-01-24 21:15:25 -0500133
Mark Beierl2bed6072023-04-05 20:01:41 +0000134 workflows = [
135 NsNoOpWorkflow,
136 VimCreateWorkflow,
137 VimDeleteWorkflow,
138 VimUpdateWorkflow,
139 ]
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000140 activities = [
141 data_activity_instance.update_vim_operation_state,
142 data_activity_instance.update_vim_state,
143 data_activity_instance.delete_vim_record,
Mark Beierl2bed6072023-04-05 20:01:41 +0000144 nslcm_activity_instance.update_ns_lcm_operation_state,
145 nslcm_activity_instance.no_op,
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000146 paas_connector_instance.test_vim_connectivity,
Mark Beierl821bfc92023-01-24 21:15:25 -0500147 ]
Mark Beierl821bfc92023-01-24 21:15:25 -0500148
Mark Beierl2bed6072023-04-05 20:01:41 +0000149 # Check if we are running under a debugger
150 debug = os.getenv("VSCODE_IPC_HOOK_CLI") is not None
151
Mark Beierl821bfc92023-01-24 21:15:25 -0500152 worker = Worker(
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000153 client,
154 task_queue=LCM_TASK_QUEUE,
155 workflows=workflows,
156 activities=activities,
Mark Beierl2bed6072023-04-05 20:01:41 +0000157 debug_mode=debug,
Mark Beierl821bfc92023-01-24 21:15:25 -0500158 )
159
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000160 self.logger.info("Starting LCM temporal worker")
Mark Beierl821bfc92023-01-24 21:15:25 -0500161 await worker.run()
162
Mark Beierl821bfc92023-01-24 21:15:25 -0500163
Mark Beierl821bfc92023-01-24 21:15:25 -0500164if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500165 try:
166 opts, args = getopt.getopt(
167 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
168 )
169 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
170 config_file = None
171 for o, a in opts:
172 if o in ("-c", "--config"):
173 config_file = a
174 else:
175 assert False, "Unhandled option"
176
177 if config_file:
178 if not path.isfile(config_file):
179 print(
180 "configuration file '{}' does not exist".format(config_file),
181 file=sys.stderr,
182 )
183 exit(1)
184 else:
185 for config_file in (
186 __file__[: __file__.rfind(".")] + ".cfg",
187 "./lcm.cfg",
188 "/etc/osm/lcm.cfg",
189 ):
190 print(f"{config_file}")
191 if path.isfile(config_file):
192 break
193 else:
194 print(
195 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
196 file=sys.stderr,
197 )
198 exit(1)
199 lcm = NGLcm(config_file)
200 asyncio.run(lcm.start())
201 except (LcmException, getopt.GetoptError) as e:
202 print(str(e), file=sys.stderr)
203 # usage()
204 exit(1)