blob: 7feb866fbb64a2267a1ce4fdf88b7230c03baf5b [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
Daniel Arndtc56d3362023-04-18 11:26:16 -030025from os import path
Mark Beierl821bfc92023-01-24 21:15:25 -050026
Daniel Arndtc56d3362023-04-18 11:26:16 -030027import yaml
Mark Beierl821bfc92023-01-24 21:15:25 -050028from osm_common.dbbase import DbException
Dario Faccinf5d65b52023-06-19 12:35:33 +020029from osm_common.temporal_task_queues.task_queues_mappings import LCM_TASK_QUEUE
Mark Beierl821bfc92023-01-24 21:15:25 -050030from osm_lcm.data_utils.database.database import Database
31from osm_lcm.data_utils.lcm_config import LcmCfg
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000032from osm_lcm.lcm_utils import LcmException
Dario Faccinf5d65b52023-06-19 12:35:33 +020033from osm_lcm.temporal.juju_paas_activities import (
34 JujuPaasConnector,
35 CreateModelImpl,
36 CheckCharmStatusImpl,
37 DeployCharmImpl,
38 TestVimConnectivityImpl,
39)
40
41from osm_lcm.temporal.lcm_activities import NsLcmNoOpImpl, UpdateNsLcmOperationStateImpl
42from osm_lcm.temporal.lcm_workflows import NsNoOpWorkflowImpl
43from osm_lcm.temporal.ns_activities import (
44 GetVnfDetailsImpl,
45 GetNsRecordImpl,
46 UpdateNsStateImpl,
47)
48from osm_lcm.temporal.ns_workflows import NsInstantiateWorkflowImpl
49from osm_lcm.temporal.vdu_workflows import VduInstantiateWorkflowImpl
50from osm_lcm.temporal.vim_activities import (
51 UpdateVimStateImpl,
52 UpdateVimOperationStateImpl,
53 DeleteVimRecordImpl,
54)
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000055from osm_lcm.temporal.vim_workflows import (
Dario Faccinf5d65b52023-06-19 12:35:33 +020056 VimCreateWorkflowImpl,
57 VimDeleteWorkflowImpl,
58 VimUpdateWorkflowImpl,
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000059)
Dario Faccin0568c6c2023-04-14 10:19:07 +020060from osm_lcm.temporal.vnf_activities import (
Dario Faccinf5d65b52023-06-19 12:35:33 +020061 GetTaskQueueImpl,
62 GetVnfDescriptorImpl,
63 GetVnfRecordImpl,
64 GetVimCloudImpl,
65 ChangeVnfStateImpl,
66 SetVnfModelImpl,
67 ChangeVnfInstantiationStateImpl,
68 SendNotificationForVnfImpl,
Dario Faccin0568c6c2023-04-14 10:19:07 +020069)
Dario Faccinf5d65b52023-06-19 12:35:33 +020070from osm_lcm.temporal.vnf_workflows import (
71 VnfInstantiateWorkflowImpl,
72 VnfPrepareWorkflowImpl,
73)
Gulsum Atici50d12e02023-04-27 16:41:43 +030074from temporalio.client import Client
75from temporalio.worker import Worker
Mark Beierl821bfc92023-01-24 21:15:25 -050076
77
78class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050079 main_config = LcmCfg()
80
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000081 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050082 """
83 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000084 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050085 :return: None
86 """
Daniel Arndt0d2142a2023-04-20 17:14:58 -030087 self.db: Database = None
Mark Beierl821bfc92023-01-24 21:15:25 -050088 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000089 self._load_configuration(config_file)
90 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050091
92 try:
93 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050094 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050095 self.logger.critical(str(e), exc_info=True)
96 raise LcmException(str(e))
97
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000098 def _load_configuration(self, config_file):
99 config = self._read_config_file(config_file)
100 self.main_config.set_from_dict(config)
101 self.main_config.transform()
102 self.main_config.load_from_env()
103 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
104
105 def _read_config_file(self, config_file):
106 try:
107 with open(config_file) as f:
108 return yaml.safe_load(f)
109 except Exception as e:
110 self.logger.critical("At config file '{}': {}".format(config_file, e))
111 exit(1)
112
113 @staticmethod
114 def _get_log_formatter_simple():
115 log_format_simple = (
116 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
117 )
118 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
119
120 def _create_file_handler(self):
121 return logging.handlers.RotatingFileHandler(
122 self.main_config.globalConfig.logfile,
123 maxBytes=100e6,
124 backupCount=9,
125 delay=0,
126 )
127
128 def _log_other_modules(self):
129 for logger in ("message", "database", "storage", "tsdb", "temporal"):
130 logger_config = self.main_config.to_dict()[logger]
131 logger_module = logging.getLogger(logger_config["logger_name"])
132 if logger_config["logfile"]:
133 file_handler = logging.handlers.RotatingFileHandler(
134 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
135 )
136 file_handler.setFormatter(self._get_log_formatter_simple())
137 logger_module.addHandler(file_handler)
138 if logger_config["loglevel"]:
139 logger_module.setLevel(logger_config["loglevel"])
Mark Beierldceed592023-04-11 21:03:56 +0000140 logging.getLogger("juju.client.connection").setLevel(logging.CRITICAL)
Patricia Reinoso199fbfc2023-03-02 08:53:58 +0000141
142 def _configure_logging(self):
143 if self.main_config.globalConfig.logfile:
144 file_handler = self._create_file_handler()
145 file_handler.setFormatter(self._get_log_formatter_simple())
146 self.logger.addHandler(file_handler)
147
148 if not self.main_config.globalConfig.to_dict()["nologging"]:
149 str_handler = logging.StreamHandler()
150 str_handler.setFormatter(self._get_log_formatter_simple())
151 self.logger.addHandler(str_handler)
152
153 if self.main_config.globalConfig.to_dict()["loglevel"]:
154 self.logger.setLevel(self.main_config.globalConfig.loglevel)
155
156 self._log_other_modules()
157 self.logger.critical("starting osm/nglcm")
158
Mark Beierl821bfc92023-01-24 21:15:25 -0500159 async def start(self):
Mark Beierl821bfc92023-01-24 21:15:25 -0500160 temporal_api = (
161 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
162 )
Mark Beierl821bfc92023-01-24 21:15:25 -0500163 client = await Client.connect(temporal_api)
Patricia Reinoso52431352023-04-05 15:35:48 +0000164
Patricia Reinoso52431352023-04-05 15:35:48 +0000165 paas_connector_instance = JujuPaasConnector(self.db)
Mark Beierl821bfc92023-01-24 21:15:25 -0500166
Mark Beierl2bed6072023-04-05 20:01:41 +0000167 workflows = [
Dario Faccinf5d65b52023-06-19 12:35:33 +0200168 NsInstantiateWorkflowImpl,
169 NsNoOpWorkflowImpl,
170 VimCreateWorkflowImpl,
171 VimDeleteWorkflowImpl,
172 VimUpdateWorkflowImpl,
173 VduInstantiateWorkflowImpl,
174 VnfInstantiateWorkflowImpl,
175 VnfPrepareWorkflowImpl,
Mark Beierl2bed6072023-04-05 20:01:41 +0000176 ]
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000177 activities = [
Dario Faccinf5d65b52023-06-19 12:35:33 +0200178 UpdateNsStateImpl(self.db).__call__,
179 GetVnfDetailsImpl(self.db).__call__,
180 GetNsRecordImpl(self.db).__call__,
181 UpdateNsLcmOperationStateImpl(self.db).__call__,
182 NsLcmNoOpImpl().__call__,
183 CreateModelImpl(self.db, paas_connector_instance).__call__,
184 DeployCharmImpl(paas_connector_instance).__call__,
185 CheckCharmStatusImpl(paas_connector_instance).__call__,
186 TestVimConnectivityImpl(paas_connector_instance).__call__,
187 UpdateVimOperationStateImpl(self.db).__call__,
188 UpdateVimStateImpl(self.db).__call__,
189 DeleteVimRecordImpl(self.db).__call__,
190 ChangeVnfStateImpl(self.db).__call__,
191 ChangeVnfInstantiationStateImpl(self.db).__call__,
192 GetTaskQueueImpl(self.db).__call__,
193 GetVimCloudImpl(self.db).__call__,
194 GetVnfDescriptorImpl(self.db).__call__,
195 GetVnfRecordImpl(self.db).__call__,
196 SendNotificationForVnfImpl().__call__,
197 SetVnfModelImpl(self.db).__call__,
Mark Beierl821bfc92023-01-24 21:15:25 -0500198 ]
Mark Beierl821bfc92023-01-24 21:15:25 -0500199
Mark Beierl2bed6072023-04-05 20:01:41 +0000200 # Check if we are running under a debugger
201 debug = os.getenv("VSCODE_IPC_HOOK_CLI") is not None
202
Mark Beierl821bfc92023-01-24 21:15:25 -0500203 worker = Worker(
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000204 client,
205 task_queue=LCM_TASK_QUEUE,
206 workflows=workflows,
207 activities=activities,
Mark Beierl2bed6072023-04-05 20:01:41 +0000208 debug_mode=debug,
Mark Beierl821bfc92023-01-24 21:15:25 -0500209 )
210
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000211 self.logger.info("Starting LCM temporal worker")
Mark Beierl821bfc92023-01-24 21:15:25 -0500212 await worker.run()
213
Mark Beierl821bfc92023-01-24 21:15:25 -0500214
Mark Beierl821bfc92023-01-24 21:15:25 -0500215if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500216 try:
217 opts, args = getopt.getopt(
218 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
219 )
220 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
221 config_file = None
222 for o, a in opts:
223 if o in ("-c", "--config"):
224 config_file = a
225 else:
226 assert False, "Unhandled option"
227
228 if config_file:
229 if not path.isfile(config_file):
230 print(
231 "configuration file '{}' does not exist".format(config_file),
232 file=sys.stderr,
233 )
234 exit(1)
235 else:
236 for config_file in (
237 __file__[: __file__.rfind(".")] + ".cfg",
238 "./lcm.cfg",
239 "/etc/osm/lcm.cfg",
240 ):
241 print(f"{config_file}")
242 if path.isfile(config_file):
243 break
244 else:
245 print(
246 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
247 file=sys.stderr,
248 )
249 exit(1)
250 lcm = NGLcm(config_file)
251 asyncio.run(lcm.start())
252 except (LcmException, getopt.GetoptError) as e:
253 print(str(e), file=sys.stderr)
254 # usage()
255 exit(1)