44cf7970ff7f9e51f3f19c315cbfec5851d46093
[releng.git] / utils / test / dashboard / dashboard / conf / config.py
1 #! /usr/bin/env python
2
3 from ConfigParser import SafeConfigParser, NoOptionError
4
5
6 class ParseError(Exception):
7     """
8     Custom exception class for config file
9     """
10
11     def __init__(self, message):
12         self.msg = message
13
14     def __str__(self):
15         return 'error parsing config file : %s' % self.msg
16
17
18 class APIConfig:
19     """
20     The purpose of this class is to load values correctly from the config file.
21     Each key is declared as an attribute in __init__() and linked in parse()
22     """
23
24     def __init__(self):
25         self._default_config_location = "/etc/dashboard/config.ini"
26         self.es_url = 'http://localhost:9200'
27         self.es_creds = None
28         self.kibana_url = None
29         self.js_path = None
30
31     def _get_str_parameter(self, section, param):
32         try:
33             return self._parser.get(section, param)
34         except NoOptionError:
35             raise ParseError("[%s.%s] parameter not found" % (section, param))
36
37     def _get_int_parameter(self, section, param):
38         try:
39             return int(self._get_str_parameter(section, param))
40         except ValueError:
41             raise ParseError("[%s.%s] not an int" % (section, param))
42
43     def _get_bool_parameter(self, section, param):
44         result = self._get_str_parameter(section, param)
45         if str(result).lower() == 'true':
46             return True
47         if str(result).lower() == 'false':
48             return False
49
50         raise ParseError(
51             "[%s.%s : %s] not a boolean" % (section, param, result))
52
53     @staticmethod
54     def parse(config_location=None):
55         obj = APIConfig()
56
57         if config_location is None:
58             config_location = obj._default_config_location
59
60         obj._parser = SafeConfigParser()
61         obj._parser.read(config_location)
62         if not obj._parser:
63             raise ParseError("%s not found" % config_location)
64
65         # Linking attributes to keys from file with their sections
66         obj.es_url = obj._get_str_parameter("elastic", "url")
67         obj.es_creds = obj._get_str_parameter("elastic", "creds")
68         obj.kibana_url = obj._get_str_parameter("kibana", "url")
69         obj.js_path = obj._get_str_parameter("kibana", "js_path")
70
71         return obj
72
73     def __str__(self):
74         return "elastic_url = %s \n" \
75                "elastic_creds = %s \n" \
76                "kibana_url = %s \n" \
77                "js_path = %s \n" % (self.es_url,
78                                     self.es_creds,
79                                     self.kibana_url,
80                                     self.js_path)