blob: 926fe79970531506682745ab09810f53e20e866c [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,
Dario Faccin83789292023-07-03 09:18:04 +020039 RemoveCharmImpl,
40 CheckCharmIsRemovedImpl,
Dario Faccinf5d65b52023-06-19 12:35:33 +020041)
42
43from osm_lcm.temporal.lcm_activities import NsLcmNoOpImpl, UpdateNsLcmOperationStateImpl
44from osm_lcm.temporal.lcm_workflows import NsNoOpWorkflowImpl
45from osm_lcm.temporal.ns_activities import (
46 GetVnfDetailsImpl,
47 GetNsRecordImpl,
48 UpdateNsStateImpl,
49)
50from osm_lcm.temporal.ns_workflows import NsInstantiateWorkflowImpl
51from osm_lcm.temporal.vdu_workflows import VduInstantiateWorkflowImpl
52from osm_lcm.temporal.vim_activities import (
53 UpdateVimStateImpl,
54 UpdateVimOperationStateImpl,
55 DeleteVimRecordImpl,
56)
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000057from osm_lcm.temporal.vim_workflows import (
Dario Faccinf5d65b52023-06-19 12:35:33 +020058 VimCreateWorkflowImpl,
59 VimDeleteWorkflowImpl,
60 VimUpdateWorkflowImpl,
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000061)
Dario Faccin0568c6c2023-04-14 10:19:07 +020062from osm_lcm.temporal.vnf_activities import (
Dario Faccinf5d65b52023-06-19 12:35:33 +020063 GetTaskQueueImpl,
64 GetVnfDescriptorImpl,
65 GetVnfRecordImpl,
66 GetVimCloudImpl,
67 ChangeVnfStateImpl,
68 SetVnfModelImpl,
69 ChangeVnfInstantiationStateImpl,
70 SendNotificationForVnfImpl,
Dario Faccin0568c6c2023-04-14 10:19:07 +020071)
Dario Faccinf5d65b52023-06-19 12:35:33 +020072from osm_lcm.temporal.vnf_workflows import (
73 VnfInstantiateWorkflowImpl,
74 VnfPrepareWorkflowImpl,
75)
Gulsum Atici50d12e02023-04-27 16:41:43 +030076from temporalio.client import Client
77from temporalio.worker import Worker
Mark Beierl821bfc92023-01-24 21:15:25 -050078
79
80class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050081 main_config = LcmCfg()
82
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000083 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050084 """
85 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000086 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050087 :return: None
88 """
Daniel Arndt0d2142a2023-04-20 17:14:58 -030089 self.db: Database = None
Mark Beierl821bfc92023-01-24 21:15:25 -050090 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000091 self._load_configuration(config_file)
92 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050093
94 try:
95 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050096 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050097 self.logger.critical(str(e), exc_info=True)
98 raise LcmException(str(e))
99
Patricia Reinoso199fbfc2023-03-02 08:53:58 +0000100 def _load_configuration(self, config_file):
101 config = self._read_config_file(config_file)
102 self.main_config.set_from_dict(config)
103 self.main_config.transform()
104 self.main_config.load_from_env()
105 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
106
107 def _read_config_file(self, config_file):
108 try:
109 with open(config_file) as f:
110 return yaml.safe_load(f)
111 except Exception as e:
112 self.logger.critical("At config file '{}': {}".format(config_file, e))
113 exit(1)
114
115 @staticmethod
116 def _get_log_formatter_simple():
117 log_format_simple = (
118 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
119 )
120 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
121
122 def _create_file_handler(self):
123 return logging.handlers.RotatingFileHandler(
124 self.main_config.globalConfig.logfile,
125 maxBytes=100e6,
126 backupCount=9,
127 delay=0,
128 )
129
130 def _log_other_modules(self):
131 for logger in ("message", "database", "storage", "tsdb", "temporal"):
132 logger_config = self.main_config.to_dict()[logger]
133 logger_module = logging.getLogger(logger_config["logger_name"])
134 if logger_config["logfile"]:
135 file_handler = logging.handlers.RotatingFileHandler(
136 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
137 )
138 file_handler.setFormatter(self._get_log_formatter_simple())
139 logger_module.addHandler(file_handler)
140 if logger_config["loglevel"]:
141 logger_module.setLevel(logger_config["loglevel"])
Mark Beierldceed592023-04-11 21:03:56 +0000142 logging.getLogger("juju.client.connection").setLevel(logging.CRITICAL)
Patricia Reinoso199fbfc2023-03-02 08:53:58 +0000143
144 def _configure_logging(self):
145 if self.main_config.globalConfig.logfile:
146 file_handler = self._create_file_handler()
147 file_handler.setFormatter(self._get_log_formatter_simple())
148 self.logger.addHandler(file_handler)
149
150 if not self.main_config.globalConfig.to_dict()["nologging"]:
151 str_handler = logging.StreamHandler()
152 str_handler.setFormatter(self._get_log_formatter_simple())
153 self.logger.addHandler(str_handler)
154
155 if self.main_config.globalConfig.to_dict()["loglevel"]:
156 self.logger.setLevel(self.main_config.globalConfig.loglevel)
157
158 self._log_other_modules()
159 self.logger.critical("starting osm/nglcm")
160
Mark Beierl821bfc92023-01-24 21:15:25 -0500161 async def start(self):
Mark Beierl821bfc92023-01-24 21:15:25 -0500162 temporal_api = (
163 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
164 )
Mark Beierl821bfc92023-01-24 21:15:25 -0500165 client = await Client.connect(temporal_api)
Patricia Reinoso52431352023-04-05 15:35:48 +0000166
Patricia Reinoso52431352023-04-05 15:35:48 +0000167 paas_connector_instance = JujuPaasConnector(self.db)
Mark Beierl821bfc92023-01-24 21:15:25 -0500168
Mark Beierl2bed6072023-04-05 20:01:41 +0000169 workflows = [
Dario Faccinf5d65b52023-06-19 12:35:33 +0200170 NsInstantiateWorkflowImpl,
171 NsNoOpWorkflowImpl,
172 VimCreateWorkflowImpl,
173 VimDeleteWorkflowImpl,
174 VimUpdateWorkflowImpl,
175 VduInstantiateWorkflowImpl,
176 VnfInstantiateWorkflowImpl,
177 VnfPrepareWorkflowImpl,
Mark Beierl2bed6072023-04-05 20:01:41 +0000178 ]
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000179 activities = [
Mark Beierl82629422023-06-29 20:22:36 +0000180 UpdateNsStateImpl(self.db),
181 GetVnfDetailsImpl(self.db),
182 GetNsRecordImpl(self.db),
183 UpdateNsLcmOperationStateImpl(self.db),
184 NsLcmNoOpImpl(),
185 CreateModelImpl(self.db, paas_connector_instance),
186 DeployCharmImpl(paas_connector_instance),
187 CheckCharmStatusImpl(paas_connector_instance),
188 TestVimConnectivityImpl(paas_connector_instance),
Dario Faccin83789292023-07-03 09:18:04 +0200189 RemoveCharmImpl(paas_connector_instance),
190 CheckCharmIsRemovedImpl(paas_connector_instance),
Mark Beierl82629422023-06-29 20:22:36 +0000191 UpdateVimOperationStateImpl(self.db),
192 UpdateVimStateImpl(self.db),
193 DeleteVimRecordImpl(self.db),
194 ChangeVnfStateImpl(self.db),
195 ChangeVnfInstantiationStateImpl(self.db),
196 GetTaskQueueImpl(self.db),
197 GetVimCloudImpl(self.db),
198 GetVnfDescriptorImpl(self.db),
199 GetVnfRecordImpl(self.db),
200 SendNotificationForVnfImpl(),
201 SetVnfModelImpl(self.db),
Mark Beierl821bfc92023-01-24 21:15:25 -0500202 ]
Mark Beierl821bfc92023-01-24 21:15:25 -0500203
Mark Beierl2bed6072023-04-05 20:01:41 +0000204 # Check if we are running under a debugger
205 debug = os.getenv("VSCODE_IPC_HOOK_CLI") is not None
206
Mark Beierl821bfc92023-01-24 21:15:25 -0500207 worker = Worker(
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000208 client,
209 task_queue=LCM_TASK_QUEUE,
210 workflows=workflows,
211 activities=activities,
Mark Beierl2bed6072023-04-05 20:01:41 +0000212 debug_mode=debug,
Mark Beierl821bfc92023-01-24 21:15:25 -0500213 )
214
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000215 self.logger.info("Starting LCM temporal worker")
Mark Beierl821bfc92023-01-24 21:15:25 -0500216 await worker.run()
217
Mark Beierl821bfc92023-01-24 21:15:25 -0500218
Mark Beierl821bfc92023-01-24 21:15:25 -0500219if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500220 try:
221 opts, args = getopt.getopt(
222 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
223 )
224 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
225 config_file = None
226 for o, a in opts:
227 if o in ("-c", "--config"):
228 config_file = a
229 else:
230 assert False, "Unhandled option"
231
232 if config_file:
233 if not path.isfile(config_file):
234 print(
235 "configuration file '{}' does not exist".format(config_file),
236 file=sys.stderr,
237 )
238 exit(1)
239 else:
240 for config_file in (
241 __file__[: __file__.rfind(".")] + ".cfg",
242 "./lcm.cfg",
243 "/etc/osm/lcm.cfg",
244 ):
245 print(f"{config_file}")
246 if path.isfile(config_file):
247 break
248 else:
249 print(
250 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
251 file=sys.stderr,
252 )
253 exit(1)
254 lcm = NGLcm(config_file)
255 asyncio.run(lcm.start())
256 except (LcmException, getopt.GetoptError) as e:
257 print(str(e), file=sys.stderr)
258 # usage()
259 exit(1)