blob: 41f767181f375b0a7b249b41c85f138df4567853 [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 Beierl9e1379d2023-04-06 15:12:46 +000043from osm_lcm.temporal.vnf_workflows import VnfInstantiateWorkflow
44from osm_lcm.temporal.vnf_activities import VnfDbActivity, VnfOperations
Mark Beierl821bfc92023-01-24 21:15:25 -050045from temporalio.client import Client
46from temporalio.worker import Worker
47
48
49class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050050 main_config = LcmCfg()
51
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000052 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050053 """
54 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000055 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050056 :return: None
57 """
58 self.db = None
Mark Beierl821bfc92023-01-24 21:15:25 -050059 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000060 self._load_configuration(config_file)
61 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050062
63 try:
64 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050065 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050066 self.logger.critical(str(e), exc_info=True)
67 raise LcmException(str(e))
68
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000069 def _load_configuration(self, config_file):
70 config = self._read_config_file(config_file)
71 self.main_config.set_from_dict(config)
72 self.main_config.transform()
73 self.main_config.load_from_env()
74 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
75
76 def _read_config_file(self, config_file):
77 try:
78 with open(config_file) as f:
79 return yaml.safe_load(f)
80 except Exception as e:
81 self.logger.critical("At config file '{}': {}".format(config_file, e))
82 exit(1)
83
84 @staticmethod
85 def _get_log_formatter_simple():
86 log_format_simple = (
87 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
88 )
89 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
90
91 def _create_file_handler(self):
92 return logging.handlers.RotatingFileHandler(
93 self.main_config.globalConfig.logfile,
94 maxBytes=100e6,
95 backupCount=9,
96 delay=0,
97 )
98
99 def _log_other_modules(self):
100 for logger in ("message", "database", "storage", "tsdb", "temporal"):
101 logger_config = self.main_config.to_dict()[logger]
102 logger_module = logging.getLogger(logger_config["logger_name"])
103 if logger_config["logfile"]:
104 file_handler = logging.handlers.RotatingFileHandler(
105 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
106 )
107 file_handler.setFormatter(self._get_log_formatter_simple())
108 logger_module.addHandler(file_handler)
109 if logger_config["loglevel"]:
110 logger_module.setLevel(logger_config["loglevel"])
111
112 def _configure_logging(self):
113 if self.main_config.globalConfig.logfile:
114 file_handler = self._create_file_handler()
115 file_handler.setFormatter(self._get_log_formatter_simple())
116 self.logger.addHandler(file_handler)
117
118 if not self.main_config.globalConfig.to_dict()["nologging"]:
119 str_handler = logging.StreamHandler()
120 str_handler.setFormatter(self._get_log_formatter_simple())
121 self.logger.addHandler(str_handler)
122
123 if self.main_config.globalConfig.to_dict()["loglevel"]:
124 self.logger.setLevel(self.main_config.globalConfig.loglevel)
125
126 self._log_other_modules()
127 self.logger.critical("starting osm/nglcm")
128
Mark Beierl821bfc92023-01-24 21:15:25 -0500129 async def start(self):
Mark Beierl821bfc92023-01-24 21:15:25 -0500130 temporal_api = (
131 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
132 )
Mark Beierl821bfc92023-01-24 21:15:25 -0500133 client = await Client.connect(temporal_api)
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000134 vim_data_activity_instance = VimDbActivity(self.db)
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000135 paas_connector_instance = JujuPaasConnector(self.db)
Mark Beierl2bed6072023-04-05 20:01:41 +0000136 nslcm_activity_instance = NsLcmActivity(self.db)
Mark Beierl9e1379d2023-04-06 15:12:46 +0000137 vnf_operation_instance = VnfOperations(self.db)
138 vnf_data_activity_instance = VnfDbActivity(self.db)
Mark Beierl821bfc92023-01-24 21:15:25 -0500139
Mark Beierl2bed6072023-04-05 20:01:41 +0000140 workflows = [
141 NsNoOpWorkflow,
142 VimCreateWorkflow,
143 VimDeleteWorkflow,
144 VimUpdateWorkflow,
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000145 VduInstantiateWorkflow,
Mark Beierl9e1379d2023-04-06 15:12:46 +0000146 VnfInstantiateWorkflow,
Mark Beierl2bed6072023-04-05 20:01:41 +0000147 ]
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000148 activities = [
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000149 vim_data_activity_instance.update_vim_operation_state,
150 vim_data_activity_instance.update_vim_state,
151 vim_data_activity_instance.delete_vim_record,
Mark Beierl2bed6072023-04-05 20:01:41 +0000152 nslcm_activity_instance.update_ns_lcm_operation_state,
153 nslcm_activity_instance.no_op,
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000154 paas_connector_instance.test_vim_connectivity,
Patricia Reinoso1fa7b6d2023-04-05 15:27:20 +0000155 paas_connector_instance.create_model_if_doesnt_exist,
156 paas_connector_instance.deploy_charm,
157 paas_connector_instance.check_charm_status,
Mark Beierl9e1379d2023-04-06 15:12:46 +0000158 vnf_operation_instance.get_task_queue,
159 vnf_data_activity_instance.change_nf_state,
160 vnf_data_activity_instance.change_nf_instantiation_state,
161 vnf_data_activity_instance.change_nf_notification_state,
Mark Beierl821bfc92023-01-24 21:15:25 -0500162 ]
Mark Beierl821bfc92023-01-24 21:15:25 -0500163
Mark Beierl2bed6072023-04-05 20:01:41 +0000164 # Check if we are running under a debugger
165 debug = os.getenv("VSCODE_IPC_HOOK_CLI") is not None
166
Mark Beierl821bfc92023-01-24 21:15:25 -0500167 worker = Worker(
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000168 client,
169 task_queue=LCM_TASK_QUEUE,
170 workflows=workflows,
171 activities=activities,
Mark Beierl2bed6072023-04-05 20:01:41 +0000172 debug_mode=debug,
Mark Beierl821bfc92023-01-24 21:15:25 -0500173 )
174
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000175 self.logger.info("Starting LCM temporal worker")
Mark Beierl821bfc92023-01-24 21:15:25 -0500176 await worker.run()
177
Mark Beierl821bfc92023-01-24 21:15:25 -0500178
Mark Beierl821bfc92023-01-24 21:15:25 -0500179if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500180 try:
181 opts, args = getopt.getopt(
182 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
183 )
184 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
185 config_file = None
186 for o, a in opts:
187 if o in ("-c", "--config"):
188 config_file = a
189 else:
190 assert False, "Unhandled option"
191
192 if config_file:
193 if not path.isfile(config_file):
194 print(
195 "configuration file '{}' does not exist".format(config_file),
196 file=sys.stderr,
197 )
198 exit(1)
199 else:
200 for config_file in (
201 __file__[: __file__.rfind(".")] + ".cfg",
202 "./lcm.cfg",
203 "/etc/osm/lcm.cfg",
204 ):
205 print(f"{config_file}")
206 if path.isfile(config_file):
207 break
208 else:
209 print(
210 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
211 file=sys.stderr,
212 )
213 exit(1)
214 lcm = NGLcm(config_file)
215 asyncio.run(lcm.start())
216 except (LcmException, getopt.GetoptError) as e:
217 print(str(e), file=sys.stderr)
218 # usage()
219 exit(1)