1 # Copyright (c) 2022 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """Configuration parsing library."""
16 from logging import getLogger
17 from pathlib import Path
20 from yaml import safe_load, YAMLError
21 from .constants import Constants
26 Parser class reponsible for loading configuration.
28 def __init__(self, configuration_file):
32 :param configuration_file: Telemetry configuration file path.
33 :type configuration_file: str
37 self.suffix = Path(configuration_file).suffix[1:].capitalize()
40 self.instance = globals()[self.suffix+"Loader"](configuration_file)
42 raise ParserError(u"Unsupported file format!")
44 self.config = FileLoader(self.instance).load()
49 Creates a File Loader object. This is the main object for interacting
50 with configuration file.
52 def __init__(self, loader):
54 File Loader class init.
56 :param loader: Loader object responsible for handling file type.
65 return self.loader.load()
70 Creates a YAML Loader object. This is the main object for interacting
73 def __init__(self, configuration_file):
75 YAML Loader class init.
77 :param configuration_file: YAML configuration file path.
78 :type configuration_file: str
80 self.configuration_file = configuration_file
86 with open(self.configuration_file, u"r") as stream:
88 return safe_load(stream)
89 except YAMLError as exc:
90 raise ParserError(str(exc))
93 class ParserError(Exception):
95 Creates a Parser Error Exception. This exception is supposed to handle
96 all the errors raised during processing.
98 def __init__(self, message):
100 Parser Error Excpetion init.
102 :param message: Exception error message.
106 self.message = message
107 getLogger("console_stderr").error(self.message)
108 sys.exit(Constants.err_telemetry_yaml)