blob: 1d60e6ebd64f58f05b44a33b8a9aa1d56d7f0707 [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 (
Dario Faccinf5d65b52023-06-19 12:35:33 +020064 GetTaskQueueImpl,
65 GetVnfDescriptorImpl,
66 GetVnfRecordImpl,
67 GetVimCloudImpl,
68 ChangeVnfStateImpl,
69 SetVnfModelImpl,
70 ChangeVnfInstantiationStateImpl,
71 SendNotificationForVnfImpl,
Dario Faccin0568c6c2023-04-14 10:19:07 +020072)
Dario Faccinf5d65b52023-06-19 12:35:33 +020073from osm_lcm.temporal.vnf_workflows import (
74 VnfInstantiateWorkflowImpl,
75 VnfPrepareWorkflowImpl,
76)
Gulsum Atici50d12e02023-04-27 16:41:43 +030077from temporalio.client import Client
78from temporalio.worker import Worker
Mark Beierl821bfc92023-01-24 21:15:25 -050079
80
81class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050082 main_config = LcmCfg()
83
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000084 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050085 """
86 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000087 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050088 :return: None
89 """
Daniel Arndt0d2142a2023-04-20 17:14:58 -030090 self.db: Database = None
Mark Beierl821bfc92023-01-24 21:15:25 -050091 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000092 self._load_configuration(config_file)
93 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050094
95 try:
96 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050097 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050098 self.logger.critical(str(e), exc_info=True)
99 raise LcmException(str(e))
100
Patricia Reinoso199fbfc2023-03-02 08:53:58 +0000101 def _load_configuration(self, config_file):
102 config = self._read_config_file(config_file)
103 self.main_config.set_from_dict(config)
104 self.main_config.transform()
105 self.main_config.load_from_env()
106 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
107
108 def _read_config_file(self, config_file):
109 try:
110 with open(config_file) as f:
111 return yaml.safe_load(f)
112 except Exception as e:
113 self.logger.critical("At config file '{}': {}".format(config_file, e))
114 exit(1)
115
116 @staticmethod
117 def _get_log_formatter_simple():
118 log_format_simple = (
119 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
120 )
121 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
122
123 def _create_file_handler(self):
124 return logging.handlers.RotatingFileHandler(
125 self.main_config.globalConfig.logfile,
126 maxBytes=100e6,
127 backupCount=9,
128 delay=0,
129 )
130
131 def _log_other_modules(self):
132 for logger in ("message", "database", "storage", "tsdb", "temporal"):
133 logger_config = self.main_config.to_dict()[logger]
134 logger_module = logging.getLogger(logger_config["logger_name"])
135 if logger_config["logfile"]:
136 file_handler = logging.handlers.RotatingFileHandler(
137 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
138 )
139 file_handler.setFormatter(self._get_log_formatter_simple())
140 logger_module.addHandler(file_handler)
141 if logger_config["loglevel"]:
142 logger_module.setLevel(logger_config["loglevel"])
Mark Beierldceed592023-04-11 21:03:56 +0000143 logging.getLogger("juju.client.connection").setLevel(logging.CRITICAL)
Patricia Reinoso199fbfc2023-03-02 08:53:58 +0000144
145 def _configure_logging(self):
146 if self.main_config.globalConfig.logfile:
147 file_handler = self._create_file_handler()
148 file_handler.setFormatter(self._get_log_formatter_simple())
149 self.logger.addHandler(file_handler)
150
151 if not self.main_config.globalConfig.to_dict()["nologging"]:
152 str_handler = logging.StreamHandler()
153 str_handler.setFormatter(self._get_log_formatter_simple())
154 self.logger.addHandler(str_handler)
155
156 if self.main_config.globalConfig.to_dict()["loglevel"]:
157 self.logger.setLevel(self.main_config.globalConfig.loglevel)
158
159 self._log_other_modules()
160 self.logger.critical("starting osm/nglcm")
161
Mark Beierl821bfc92023-01-24 21:15:25 -0500162 async def start(self):
Mark Beierl821bfc92023-01-24 21:15:25 -0500163 temporal_api = (
164 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
165 )
Mark Beierl821bfc92023-01-24 21:15:25 -0500166 client = await Client.connect(temporal_api)
Patricia Reinoso52431352023-04-05 15:35:48 +0000167
Patricia Reinoso52431352023-04-05 15:35:48 +0000168 paas_connector_instance = JujuPaasConnector(self.db)
Mark Beierl821bfc92023-01-24 21:15:25 -0500169
Mark Beierl2bed6072023-04-05 20:01:41 +0000170 workflows = [
Dario Faccinf5d65b52023-06-19 12:35:33 +0200171 NsInstantiateWorkflowImpl,
172 NsNoOpWorkflowImpl,
173 VimCreateWorkflowImpl,
174 VimDeleteWorkflowImpl,
175 VimUpdateWorkflowImpl,
176 VduInstantiateWorkflowImpl,
177 VnfInstantiateWorkflowImpl,
178 VnfPrepareWorkflowImpl,
Mark Beierl2bed6072023-04-05 20:01:41 +0000179 ]
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000180 activities = [
Mark Beierl82629422023-06-29 20:22:36 +0000181 UpdateNsStateImpl(self.db),
182 GetVnfDetailsImpl(self.db),
183 GetNsRecordImpl(self.db),
184 UpdateNsLcmOperationStateImpl(self.db),
185 NsLcmNoOpImpl(),
186 CreateModelImpl(self.db, paas_connector_instance),
187 DeployCharmImpl(paas_connector_instance),
188 CheckCharmStatusImpl(paas_connector_instance),
189 TestVimConnectivityImpl(paas_connector_instance),
Dario Faccin83789292023-07-03 09:18:04 +0200190 RemoveCharmImpl(paas_connector_instance),
191 CheckCharmIsRemovedImpl(paas_connector_instance),
Dario Faccinea6f8172023-07-06 08:47:38 +0200192 ResolveCharmErrorsImpl(paas_connector_instance),
Mark Beierl82629422023-06-29 20:22:36 +0000193 UpdateVimOperationStateImpl(self.db),
194 UpdateVimStateImpl(self.db),
195 DeleteVimRecordImpl(self.db),
196 ChangeVnfStateImpl(self.db),
197 ChangeVnfInstantiationStateImpl(self.db),
198 GetTaskQueueImpl(self.db),
199 GetVimCloudImpl(self.db),
200 GetVnfDescriptorImpl(self.db),
201 GetVnfRecordImpl(self.db),
202 SendNotificationForVnfImpl(),
203 SetVnfModelImpl(self.db),
Mark Beierl821bfc92023-01-24 21:15:25 -0500204 ]
Mark Beierl821bfc92023-01-24 21:15:25 -0500205
Mark Beierl2bed6072023-04-05 20:01:41 +0000206 # Check if we are running under a debugger
207 debug = os.getenv("VSCODE_IPC_HOOK_CLI") is not None
208
Mark Beierl821bfc92023-01-24 21:15:25 -0500209 worker = Worker(
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000210 client,
211 task_queue=LCM_TASK_QUEUE,
212 workflows=workflows,
213 activities=activities,
Mark Beierl2bed6072023-04-05 20:01:41 +0000214 debug_mode=debug,
Mark Beierl821bfc92023-01-24 21:15:25 -0500215 )
216
Patricia Reinoso02a39fd2023-03-08 17:13:56 +0000217 self.logger.info("Starting LCM temporal worker")
Mark Beierl821bfc92023-01-24 21:15:25 -0500218 await worker.run()
219
Mark Beierl821bfc92023-01-24 21:15:25 -0500220
Mark Beierl821bfc92023-01-24 21:15:25 -0500221if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500222 try:
223 opts, args = getopt.getopt(
224 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
225 )
226 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
227 config_file = None
228 for o, a in opts:
229 if o in ("-c", "--config"):
230 config_file = a
231 else:
232 assert False, "Unhandled option"
233
234 if config_file:
235 if not path.isfile(config_file):
236 print(
237 "configuration file '{}' does not exist".format(config_file),
238 file=sys.stderr,
239 )
240 exit(1)
241 else:
242 for config_file in (
243 __file__[: __file__.rfind(".")] + ".cfg",
244 "./lcm.cfg",
245 "/etc/osm/lcm.cfg",
246 ):
247 print(f"{config_file}")
248 if path.isfile(config_file):
249 break
250 else:
251 print(
252 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
253 file=sys.stderr,
254 )
255 exit(1)
256 lcm = NGLcm(config_file)
257 asyncio.run(lcm.start())
258 except (LcmException, getopt.GetoptError) as e:
259 print(str(e), file=sys.stderr)
260 # usage()
261 exit(1)