1 # Copyright (c) 2021 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
25 Parser class reponsible for loading configuration.
27 def __init__(self, configuration_file):
31 :param configuration_file: Telemetry configuration file path.
32 :type configuration_file: str
36 self.suffix = Path(configuration_file).suffix[1:].capitalize()
39 self.instance = globals()[self.suffix+"Loader"](configuration_file)
41 raise ParserError(u"Unsupported file format!")
43 self.config = FileLoader(self.instance).load()
48 Creates a File Loader object. This is the main object for interacting
49 with configuration file.
51 def __init__(self, loader):
53 File Loader class init.
55 :param loader: Loader object responsible for handling file type.
64 return self.loader.load()
69 Creates a YAML Loader object. This is the main object for interacting
72 def __init__(self, configuration_file):
74 YAML Loader class init.
76 :param configuration_file: YAML configuration file path.
77 :type configuration_file: str
79 self.configuration_file = configuration_file
85 with open(self.configuration_file, u"r") as stream:
87 return safe_load(stream)
88 except YAMLError as exc:
89 raise ParserError(str(exc))
92 class ParserError(Exception):
94 Creates a Parser Error Exception. This exception is supposed to handle
95 all the errors raised during processing.
97 def __init__(self, message):
99 Parser Error Excpetion init.
101 :param message: Exception error message.
105 self.message = message
106 getLogger(__name__).error(self.message)