summaryrefslogtreecommitdiffstats
path: root/rteval/rtevalConfig.py
blob: 6c933f78c55e77e6cf316418d72f6ae501d41629 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#
#   rteval - script for evaluating platform suitability for RT Linux
#
#           This program is used to determine the suitability of
#           a system for use in a Real Time Linux environment.
#           It starts up various system loads and measures event
#           latency while the loads are running. A report is generated
#           to show the latencies encountered during the run.
#
#   Copyright 2009   Clark Williams <williams@redhat.com>
#   Copyright 2009   David Sommerseth <davids@redhat.com>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#
#   For the avoidance of doubt the "preferred form" of this code is one which
#   is in an open unpatent encumbered format. Where cryptographic key signing
#   forms part of the process of creating an executable the information
#   including keys needed to generate an equivalently functional executable
#   are deemed to be part of the source code.
#
import os
import ConfigParser

class rtevalCfgSection(object):

    def __init__(self, section_cfg):
        self.__update_config_vars(section_cfg)
        self.__iter_list = None

    def __str__(self):
        "Simple method for dumping config when object is used as a string"
        return str(self.__cfgdata)

    def __update_config_vars(self, section_cfg):
        if section_cfg is None:
            return
        self.__cfgdata = section_cfg

        # create member variables from config info
        for m in section_cfg.keys():
            self.__dict__[m] = section_cfg[m]


    def __iter__(self):
        "Initialises for an iterator loop"
        self.__iter_list = self.keys()
        return self


    def next(self):
        "Function used by the iterator"
        if len(self.__iter_list) == 0:
            raise StopIteration
        else:
            elmt = self.__iter_list.pop()
            return (elmt, self.__cfgdata[elmt])


    def has_key(self, key):
        "has_key() wrapper for the configuration data"
        return self.__cfgdata.has_key(key)


    def keys(self):
        "keys() wrapper for configuration data"
        return self.__cfgdata.keys()

    def setdefault(self, key, defvalue):
        if not self.__dict__.has_key(key):
            self.__dict__[key] = defvalue
        return self.__dict__[key]

class rtevalConfig(rtevalCfgSection):
    "Config parser for rteval"

    def __init__(self, initvars = None, logfunc = None):
        self.__config_data = initvars or {}
        self.__config_files = []

        # export the rteval section to member variables, if section is found
        try:
            self._rtevalCfgSection__update_config_vars(self.__config_data['rteval'])
        except KeyError:
            pass  # If 'rteval' is not found, KeyError is raised and that's okay to ignore
        except Exception, err:
            raise err # All other errors will be passed on

        self.__info = logfunc or self.__nolog


    def __str__(self):
        "Simple method for dumping config when object is used as a string"
        return str(self.__config_data)


    def __nolog(self, str):
        "Dummy log function, used when no log function is configured"
        pass


    def __find_config(self):
        "locate a config file"

        for f in ('rteval.conf', '/etc/rteval.conf'):
            p = os.path.abspath(f)
            if os.path.exists(p):
                self.__info("found config file %s" % p)
                return p
        raise RuntimeError, "Unable to find configfile"


    def Load(self, fname = None, append = False):
        "read and parse the configfile"

        try:
            cfgfile = fname or self.__find_config()
        except:
            self.__info("no config file")
            return

        if self.ConfigParsed(cfgfile) is True:
            # Don't try to reread this file if it's already been parsed
            return

        self.__info("reading config file %s" % cfgfile)
        ini = ConfigParser.ConfigParser()
        ini.read(cfgfile)

        # wipe any previously read config info (other than the rteval stuff)
        if not append:
            for s in self.__config_data.keys():
                if s == 'rteval':
                    continue
                self.__config_data[s] = {}

        # copy the section data into the __config_data dictionary
        for s in ini.sections():
            if not self.__config_data.has_key(s):
                self.__config_data[s] = {}
            for i in ini.items(s):
                self.__config_data[s][i[0]] = i[1]

        # export the rteval section to member variables
        try:
            self._rtevalCfgSection__update_config_vars(self.__config_data['rteval'])
        except KeyError:
            pass
        except Exception, err:
            raise err

        # Register the file as read
        self.__config_files.append(cfgfile)
        return cfgfile

    def ConfigParsed(self, fname):
        "Returns True if the config file given by name has already been parsed"
        return self.__config_files.__contains__(fname)


    def AppendConfig(self, section, cfgvars):
        "Add more config parameters to a section.  cfgvard must be a dictionary of parameters"

        if type(cfgvars) is dict:
            for o in cfgvars.keys():
                self.__config_data[section][o] = cfgvars[o]
        else:
            for o in cfgvars.__dict__.keys():
                self.__config_data[section][o] = cfgvars.__dict__[o]

        if section == 'rteval':
            self._rtevalCfgSection__update_config_vars(self.__config_data['rteval'])


    def HasSection(self, section):
        return self.__config_data.has_key(section)


    def GetSection(self, section):
        try:
            # Return a new object with config settings of a given section
            return rtevalCfgSection(self.__config_data[section])
        except KeyError, err:
            raise KeyError("The section '%s' does not exist in the config file" % section)


def unit_test(rootdir):
    try:
        cfg = rtevalConfig()
        cfg.Load(rootdir + '/rteval/rteval.conf')
        print cfg
        return 0
    except Exception, e:
        print "** EXCEPTION %s", str(e)
        return 1


if __name__ == '__main__':
    import sys
    sys.exit(unit_test('..'))