blob: ee758cb93f078df20c6c9295319831a552d0b40e [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
23import sys
24import yaml
25
Mark Beierl821bfc92023-01-24 21:15:25 -050026from osm_common.dbbase import DbException
27from osm_lcm.data_utils.database.database import Database
28from osm_lcm.data_utils.lcm_config import LcmCfg
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000029from osm_lcm.lcm_utils import LcmException
Mark Beierl821bfc92023-01-24 21:15:25 -050030from os import path
31from temporalio import workflow
32from temporalio.client import Client
33from temporalio.worker import Worker
34
35
36class NGLcm:
Mark Beierl821bfc92023-01-24 21:15:25 -050037 main_config = LcmCfg()
38
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000039 def __init__(self, config_file):
Mark Beierl821bfc92023-01-24 21:15:25 -050040 """
41 Init, Connect to database, filesystem storage, and messaging
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000042 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
Mark Beierl821bfc92023-01-24 21:15:25 -050043 :return: None
44 """
45 self.db = None
Mark Beierl821bfc92023-01-24 21:15:25 -050046 self.logger = logging.getLogger("lcm")
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000047 self._load_configuration(config_file)
48 self._configure_logging()
Mark Beierl821bfc92023-01-24 21:15:25 -050049
50 try:
51 self.db = Database(self.main_config.to_dict()).instance.db
Mark Beierl90f700d2023-02-09 15:01:33 -050052 except DbException as e:
Mark Beierl821bfc92023-01-24 21:15:25 -050053 self.logger.critical(str(e), exc_info=True)
54 raise LcmException(str(e))
55
Patricia Reinoso199fbfc2023-03-02 08:53:58 +000056 def _load_configuration(self, config_file):
57 config = self._read_config_file(config_file)
58 self.main_config.set_from_dict(config)
59 self.main_config.transform()
60 self.main_config.load_from_env()
61 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
62
63 def _read_config_file(self, config_file):
64 try:
65 with open(config_file) as f:
66 return yaml.safe_load(f)
67 except Exception as e:
68 self.logger.critical("At config file '{}': {}".format(config_file, e))
69 exit(1)
70
71 @staticmethod
72 def _get_log_formatter_simple():
73 log_format_simple = (
74 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
75 )
76 return logging.Formatter(log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S")
77
78 def _create_file_handler(self):
79 return logging.handlers.RotatingFileHandler(
80 self.main_config.globalConfig.logfile,
81 maxBytes=100e6,
82 backupCount=9,
83 delay=0,
84 )
85
86 def _log_other_modules(self):
87 for logger in ("message", "database", "storage", "tsdb", "temporal"):
88 logger_config = self.main_config.to_dict()[logger]
89 logger_module = logging.getLogger(logger_config["logger_name"])
90 if logger_config["logfile"]:
91 file_handler = logging.handlers.RotatingFileHandler(
92 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
93 )
94 file_handler.setFormatter(self._get_log_formatter_simple())
95 logger_module.addHandler(file_handler)
96 if logger_config["loglevel"]:
97 logger_module.setLevel(logger_config["loglevel"])
98
99 def _configure_logging(self):
100 if self.main_config.globalConfig.logfile:
101 file_handler = self._create_file_handler()
102 file_handler.setFormatter(self._get_log_formatter_simple())
103 self.logger.addHandler(file_handler)
104
105 if not self.main_config.globalConfig.to_dict()["nologging"]:
106 str_handler = logging.StreamHandler()
107 str_handler.setFormatter(self._get_log_formatter_simple())
108 self.logger.addHandler(str_handler)
109
110 if self.main_config.globalConfig.to_dict()["loglevel"]:
111 self.logger.setLevel(self.main_config.globalConfig.loglevel)
112
113 self._log_other_modules()
114 self.logger.critical("starting osm/nglcm")
115
Mark Beierl821bfc92023-01-24 21:15:25 -0500116 async def start(self):
117 # do some temporal stuff here
118 temporal_api = (
119 f"{self.main_config.temporal.host}:{str(self.main_config.temporal.port)}"
120 )
121 self.logger.info(f"Attempting to register with Temporal at {temporal_api}")
122 client = await Client.connect(temporal_api)
123
124 task_queue = "lcm-task-queue"
125 workflows = [
126 Heartbeat,
127 ]
128 activities = []
129
130 worker = Worker(
131 client, task_queue=task_queue, workflows=workflows, activities=activities
132 )
133
134 self.logger.info(f"Registered for queue {task_queue}")
135 self.logger.info(f"Registered workflows {workflows}")
136 self.logger.info(f"Registered activites {activities}")
137
138 await worker.run()
139
Mark Beierl821bfc92023-01-24 21:15:25 -0500140
141@workflow.defn
142class Heartbeat:
143 @workflow.run
144 async def run(self) -> str:
145 return "alive"
146
147
148if __name__ == "__main__":
Mark Beierl821bfc92023-01-24 21:15:25 -0500149 try:
150 opts, args = getopt.getopt(
151 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
152 )
153 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
154 config_file = None
155 for o, a in opts:
156 if o in ("-c", "--config"):
157 config_file = a
158 else:
159 assert False, "Unhandled option"
160
161 if config_file:
162 if not path.isfile(config_file):
163 print(
164 "configuration file '{}' does not exist".format(config_file),
165 file=sys.stderr,
166 )
167 exit(1)
168 else:
169 for config_file in (
170 __file__[: __file__.rfind(".")] + ".cfg",
171 "./lcm.cfg",
172 "/etc/osm/lcm.cfg",
173 ):
174 print(f"{config_file}")
175 if path.isfile(config_file):
176 break
177 else:
178 print(
179 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
180 file=sys.stderr,
181 )
182 exit(1)
183 lcm = NGLcm(config_file)
184 asyncio.run(lcm.start())
185 except (LcmException, getopt.GetoptError) as e:
186 print(str(e), file=sys.stderr)
187 # usage()
188 exit(1)