blob: 680ffe68fedd3db46c0e941f811f282d45691b26 [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 Faccinea6f8172023-07-06 08:47:38 +020041 ResolveCharmErrorsImpl,
Dario Faccinf5d65b52023-06-19 12:35:33 +020042)
43
44from osm_lcm.temporal.lcm_activities import NsLcmNoOpImpl, UpdateNsLcmOperationStateImpl
45from osm_lcm.temporal.lcm_workflows import NsNoOpWorkflowImpl
46from osm_lcm.temporal.ns_activities import (
47 GetVnfDetailsImpl,
48 GetNsRecordImpl,
49 UpdateNsStateImpl,
50)
51from osm_lcm.temporal.ns_workflows import NsInstantiateWorkflowImpl
52from osm_lcm.temporal.vdu_workflows import VduInstantiateWorkflowImpl
53from osm_lcm.temporal.vim_activities import (
54 UpdateVimStateImpl,
55 UpdateVimOperationStateImpl,
56 DeleteVimRecordImpl,
57)
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000058from osm_lcm.temporal.vim_workflows import (
Dario Faccinf5d65b52023-06-19 12:35:33 +020059 VimCreateWorkflowImpl,
60 VimDeleteWorkflowImpl,
61 VimUpdateWorkflowImpl,
Patricia Reinoso02a39fd2023-03-08 17:13:56 +000062)
Dario Faccin0568c6c2023-04-14 10:19:07 +020063from osm_lcm.temporal.vnf_activities import (
Patricia Reinoso14406d22023-07-11 15:17:49 +000064 DeleteVnfRecordImpl,
Dario Faccinf5d65b52023-06-19 12:35:33 +020065 GetTaskQueueImpl,
66 GetVnfDescriptorImpl,
67 GetVnfRecordImpl,
68 GetVimCloudImpl,
69 ChangeVnfStateImpl,
70 SetVnfModelImpl,
71 ChangeVnfInstantiationStateImpl,
72 SendNotificationForVnfImpl,
Dario Faccin0568c6c2023-04-14 10:19:07 +020073)
Dario Faccinf5d65b52023-06-19 12:35:33 +020074from osm_lcm.temporal.vnf_workflows import (
75 VnfInstantiateWorkflowImpl,
76 VnfPrepareWorkflowImpl,
77)
Gulsum Atici50d12e02023-04-27 16:41:43 +030078from temporalio.client import Client
79from temporalio.worker import Worker
Mark Beierl821bfc92023-01-24 21:15:25 -050080
81
82class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050083 main_config = LcmCfg()
84
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000085 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050086 """
87 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000088 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050089 :return: None
90 """
Daniel Arndt0d2142a2023-04-20 17:14:58 -030091 self.db: Database = None
Mark Beierl821bfc92023-01-24 21:15:25 -050092 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000093 self._load_configuration(config_file)
94 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050095
96 try:
97 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050098 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050099 self.logger.critical(str(e), exc_info=True)
100 raise LcmException(str(e))
101
Patricia Reinoso199fbfc2023-03-02 08:53:58 +0000102 def _load_configuration(self, config_file):
103 config = self._read_config_file(config_file)
104 self.main_config.set_from_dict(config)
105 self.main_config.transform()
106 self.main_config.load_from_env()
107 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
108
109 def _read_config_file(self, config_file):
110 try:
111 with open(config_file) as f:
112 return yaml.safe_load(f)
113 except Exception as e:
114 self.logger.critical("At config file '{}': {}".format(config_file, e))
115 exit(1)
116
117 @staticmethod
118 def _get_log_formatter_simple():
119 log_format_simple = (
120 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
121 )
122 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
123
124 def _create_file_handler(self):
125 return logging.handlers.RotatingFileHandler(
126 self.main_config.globalConfig.logfile,
127 maxBytes=100e6,
128 backupCount=9,
129 delay=0,
130 )
131
132 def _log_other_modules(self):
133 for logger in ("message", "database", "storage", "tsdb", "temporal"):
134 logger_config = self.main_config.to_dict()[logger]
135 logger_module = logging.getLogger(logger_config["logger_name"])
136 if logger_config["logfile"]:
137 file_handler = logging.handlers.RotatingFileHandler(
138 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
139 )
140 file_handler.setFormatter(self._get_log_formatter_simple())
141 logger_module.addHandler(file_handler)
142 if logger_config["loglevel"]:
143 logger_module.setLevel(logger_config["loglevel"])
Mark Beierldceed592023-04-11 21:03:56 +0000144 logging.getLogger("juju.client.connection").setLevel(logging.CRITICAL)
Patricia Reinoso199fbfc2023-03-02 08:53:58 +0000145
146 def _configure_logging(self):
147 if self.main_config.globalConfig.logfile:
148 file_handler = self._create_file_handler()
149 file_handler.setFormatter(self._get_log_formatter_simple())
150 self.logger.addHandler(file_handler)
151
152 if not self.main_config.globalConfig.to_dict()["nologging"]:
153 str_handler = logging.StreamHandler()
154 str_handler.setFormatter(self._get_log_formatter_simple())
155 self.logger.addHandler(str_handler)
156
157 if self.main_config.globalConfig.to_dict()["loglevel"]:
158 self.logger.setLevel(self.main_config.globalConfig.loglevel)
159
160 self._log_other_modules()
161 self.logger.critical("starting osm/nglcm")
162
Mark Beierl821bfc92023-01-24 21:15:25 -0500163 async def start(self):
Mark Beierl821bfc92023-01-24 21:15:25 -0500164 temporal_api = (
165 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
166 )
Mark Beierl821bfc92023-01-24 21:15:25 -0500167 client = await Client.connect(temporal_api)
Patricia Reinoso52431352023-04-05 15:35:48 +0000168
Patricia Reinoso52431352023-04-05 15:35:48 +0000169 paas_connector_instance = JujuPaasConnector(self.db)
Mark Beierl821bfc92023-01-24 21:15:25 -0500170
Mark Beierl2bed6072023-04-05 20:01:41 +0000171 workflows = [
Dario Faccinf5d65b52023-06-19 12:35:33 +0200172 NsInstantiateWorkflowImpl,
173 NsNoOpWorkflowImpl,
174 VimCreateWorkflowImpl,
175 VimDeleteWorkflowImpl,
176 VimUpdateWorkflowImpl,
177 VduInstantiateWorkflowImpl,
178 VnfInstantiateWorkflowImpl,
179 VnfPrepareWorkflowImpl,
Mark Beierl2bed6072023-04-05 20:01:41 +0000180 ]
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000181 activities = [
Mark Beierl82629422023-06-29 20:22:36 +0000182 UpdateNsStateImpl(self.db),
183 GetVnfDetailsImpl(self.db),
184 GetNsRecordImpl(self.db),
185 UpdateNsLcmOperationStateImpl(self.db),
186 NsLcmNoOpImpl(),
187 CreateModelImpl(self.db, paas_connector_instance),
188 DeployCharmImpl(paas_connector_instance),
189 CheckCharmStatusImpl(paas_connector_instance),
190 TestVimConnectivityImpl(paas_connector_instance),
Dario Faccin83789292023-07-03 09:18:04 +0200191 RemoveCharmImpl(paas_connector_instance),
192 CheckCharmIsRemovedImpl(paas_connector_instance),
Dario Faccinea6f8172023-07-06 08:47:38 +0200193 ResolveCharmErrorsImpl(paas_connector_instance),
Mark Beierl82629422023-06-29 20:22:36 +0000194 UpdateVimOperationStateImpl(self.db),
195 UpdateVimStateImpl(self.db),
196 DeleteVimRecordImpl(self.db),
197 ChangeVnfStateImpl(self.db),
198 ChangeVnfInstantiationStateImpl(self.db),
Patricia Reinoso14406d22023-07-11 15:17:49 +0000199 DeleteVnfRecordImpl(self.db),
Mark Beierl82629422023-06-29 20:22:36 +0000200 GetTaskQueueImpl(self.db),
201 GetVimCloudImpl(self.db),
202 GetVnfDescriptorImpl(self.db),
203 GetVnfRecordImpl(self.db),
204 SendNotificationForVnfImpl(),
205 SetVnfModelImpl(self.db),
Mark Beierl821bfc92023-01-24 21:15:25 -0500206 ]
Mark Beierl821bfc92023-01-24 21:15:25 -0500207
Mark Beierl2bed6072023-04-05 20:01:41 +0000208 # Check if we are running under a debugger
209 debug = os.getenv("VSCODE_IPC_HOOK_CLI") is not None
210
Mark Beierl821bfc92023-01-24 21:15:25 -0500211 worker = Worker(
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000212 client,
213 task_queue=LCM_TASK_QUEUE,
214 workflows=workflows,
215 activities=activities,
Mark Beierl2bed6072023-04-05 20:01:41 +0000216 debug_mode=debug,
Mark Beierl821bfc92023-01-24 21:15:25 -0500217 )
218
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000219 self.logger.info("Starting LCM temporal worker")
Mark Beierl821bfc92023-01-24 21:15:25 -0500220 await worker.run()
221
Mark Beierl821bfc92023-01-24 21:15:25 -0500222
Mark Beierl821bfc92023-01-24 21:15:25 -0500223if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500224 try:
225 opts, args = getopt.getopt(
226 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
227 )
228 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
229 config_file = None
230 for o, a in opts:
231 if o in ("-c", "--config"):
232 config_file = a
233 else:
234 assert False, "Unhandled option"
235
236 if config_file:
237 if not path.isfile(config_file):
238 print(
239 "configuration file '{}' does not exist".format(config_file),
240 file=sys.stderr,
241 )
242 exit(1)
243 else:
244 for config_file in (
245 __file__[: __file__.rfind(".")] + ".cfg",
246 "./lcm.cfg",
247 "/etc/osm/lcm.cfg",
248 ):
249 print(f"{config_file}")
250 if path.isfile(config_file):
251 break
252 else:
253 print(
254 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
255 file=sys.stderr,
256 )
257 exit(1)
258 lcm = NGLcm(config_file)
259 asyncio.run(lcm.start())
260 except (LcmException, getopt.GetoptError) as e:
261 print(str(e), file=sys.stderr)
262 # usage()
263 exit(1)