| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 1 | #!/usr/bin/python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | |
| 4 | ## |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 5 | # |
| 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 Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 19 | import asyncio |
| 20 | import getopt |
| 21 | import logging |
| 22 | import logging.handlers |
| 23 | import sys |
| 24 | import yaml |
| 25 | |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 26 | from osm_common.dbbase import DbException |
| 27 | from osm_lcm.data_utils.database.database import Database |
| 28 | from osm_lcm.data_utils.lcm_config import LcmCfg |
| Patricia Reinoso | 199fbfc | 2023-03-02 08:53:58 +0000 | [diff] [blame] | 29 | from osm_lcm.lcm_utils import LcmException |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 30 | from os import path |
| 31 | from temporalio import workflow |
| 32 | from temporalio.client import Client |
| 33 | from temporalio.worker import Worker |
| 34 | |
| 35 | |
| 36 | class NGLcm: |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 37 | main_config = LcmCfg() |
| 38 | |
| Patricia Reinoso | 199fbfc | 2023-03-02 08:53:58 +0000 | [diff] [blame] | 39 | def __init__(self, config_file): |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 40 | """ |
| 41 | Init, Connect to database, filesystem storage, and messaging |
| Patricia Reinoso | 199fbfc | 2023-03-02 08:53:58 +0000 | [diff] [blame] | 42 | :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage', |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 43 | :return: None |
| 44 | """ |
| 45 | self.db = None |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 46 | self.logger = logging.getLogger("lcm") |
| Patricia Reinoso | 199fbfc | 2023-03-02 08:53:58 +0000 | [diff] [blame] | 47 | self._load_configuration(config_file) |
| 48 | self._configure_logging() |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 49 | |
| 50 | try: |
| 51 | self.db = Database(self.main_config.to_dict()).instance.db |
| Mark Beierl | 90f700d | 2023-02-09 15:01:33 -0500 | [diff] [blame] | 52 | except DbException as e: |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 53 | self.logger.critical(str(e), exc_info=True) |
| 54 | raise LcmException(str(e)) |
| 55 | |
| Patricia Reinoso | 199fbfc | 2023-03-02 08:53:58 +0000 | [diff] [blame] | 56 | 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 Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 116 | 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 Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 140 | |
| 141 | @workflow.defn |
| 142 | class Heartbeat: |
| 143 | @workflow.run |
| 144 | async def run(self) -> str: |
| 145 | return "alive" |
| 146 | |
| 147 | |
| 148 | if __name__ == "__main__": |
| Mark Beierl | 821bfc9 | 2023-01-24 21:15:25 -0500 | [diff] [blame] | 149 | 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) |