summaryrefslogtreecommitdiffstats
path: root/SharedModules/Parser/parser.py
blob: ee3a2d1e0df53c3129efbd08a4d87f7a354ee315 (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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
""" Parser module contains parsers for parsing:
*) TestrunInfo file
*) TestEnvironment file
*) Testcaselist file. 
"""

import ConfigParser
import re
from collections import OrderedDict
import os
from atfglobals import GlobalObj


def verify_necessary_options(cp, section, necessary_options):
    """Helper function for all parsers to verify necessary options
    in a section of the config file.

    Parameters:
        cp : Config Parser Object
        section: name of the section in ConfigFile
        necessary_options: Options necessary under Section 'section'

    Returns:
        Success: True (if all necessary_options are found in 'section')
        Failure: False ( if any of the necessaty_options not found in 'section')
    """
    all_options_found = True
    items = dict(cp.items(section))
    for option in necessary_options:
        if not (items.has_key(option) and items[option]):
            print "' %s ' Should be defined in Section: %s" % (option, section)
            all_options_found = False
    return all_options_found
        

def parse_testrun_info_file(filename):
    """
    Parse TestrunInfo File
    """
    GlobalObj.initTestrunInfoObj()
    testruninfo_obj = GlobalObj.getTestrunInfoObj()
    cp = ConfigParser.SafeConfigParser()
    necessary_sections = ["keywords", "testunits", "atfdir",
                          "summarylog","detaillog", "stdoutlog",
                          "glusterversion"]
    matched_sections = []
    unmatched_sections = []

    if not cp.read(filename):
        print "Error reading file ' %s '.File  Not found " % filename
        return 1
    else:
        available_sections = cp.sections()
        found_all_sections = True
        for section in necessary_sections:
            matched_obj = re.search(section, str(available_sections),
                                    re.IGNORECASE)
            if not matched_obj:
                found_all_sections = False
                unmatched_sections.append(section)
            else:
                matched_sections.append(matched_obj.group(0))
                
        if not found_all_sections:
            for section in unmatched_sections:
                print "Section %s Not Found" % section
            print "Please define the above sections in TestRunInfo File"
            return 1
        
        else:
            for section in matched_sections:
                Map = {}
                if re.match("keywords", section, re.IGNORECASE):
                    Map = dict(cp.items(section))
                    testruninfo_obj.addKeywords(Map['keywords'])
                        
                elif re.match("testunits", section, re.IGNORECASE):
                    Map = dict(cp.items(section))
                    testunits = Map.values()
                    for testunit in testunits:
                        if testunit:
                            testruninfo_obj.addTestUnits(testunit)

                elif re.match("atfdir", section, re.IGNORECASE):
                    Map = dict(cp.items(section))
                    atfdir = Map['dir']
                    if not atfdir:
                        print "dir option not defined in ATFDir. " + \
                              "The 'dir'option should be defined"
                        return 1
                    else:
                        testruninfo_obj.addAtfDir(atfdir)

                elif re.match("summarylog", section, re.IGNORECASE):
                    Map = dict(cp.items(section))
                    testruninfo_obj.addSummaryLogInfo(Map['filename'],
                                                      Map['loglevel'])

                elif re.match("detaillog", section, re.IGNORECASE):
                    Map = dict(cp.items(section))
                    testruninfo_obj.addDetailLogInfo(Map['filename'],
                                                      Map['loglevel'])

                elif re.match("stdoutlog", section, re.IGNORECASE):
                    Map = dict(cp.items(section))
                    testruninfo_obj.addStdoutLogInfo(Map['do_log'],
                                                      Map['loglevel'])

                elif re.match("glusterversion", section, re.IGNORECASE):
                    Map = dict(cp.items(section))
                    glusterversion = Map['version']
                    if not glusterversion:
                        print "version option not defined in GlusterVersion. " + \
                        "The 'version' option should be defined"
                        return 1
                    else:
                        testruninfo_obj.addGlusterVersion(glusterversion)

            return 0

def parse_testcaseslist_file(filename):
    """
    Parse TestCasesList file
    """
    return_status = 1
    testcaseslist = []
    if not os.path.exists(filename):
        print "%s file not found." % filename
        return return_status

    testruninfo_obj = GlobalObj.getTestrunInfoObj()
    glusterversion = testruninfo_obj.getGlusterVersion()

    testcaseslistfile = open(filename, "r")
    filedata = testcaseslistfile.readlines()

    testcaseslist = []
    for data in filedata:
        if (not data.strip() or re.match("^#", data)):
            continue

        else:
            testcaseid, version, keyword = (value.strip() for value in
                                            data.split(':'))
            testcaseslist.append({'testcaseid':testcaseid, 'version':version,
                                  'keyword':keyword})

    selected_testcases = []
    if glusterversion == "master":
        for testcase in testcaseslist:
            selected_testcases.append(testcase['testcaseid'])
        return selected_testcases
    else:
        for testcase in testcaseslist:
            if re.match("^(<|>|=|<=|>=)", testcase['version']):
                condition, version = (x.strip() for x in
                                      testcase['version'].split())
                                 
                if ((condition == "<=" and glusterversion <= version) or
                    (condition == ">=" and glusterversion >= version) or
                    (condition == "<" and glusterversion < version) or
                    (condition == ">" and glusterversion > version) or
                    (condition == "=" and glusterversion == version)):
                    selected_testcases.append(testcase['testcaseid'])

            elif re.search("-", testcaseid['version']):
                fromversion, toversion = (x.strip() for x in
                                          testcaseid['version'].split("-"))
                if (glusterversion >= fromversion and
                    glusterversion <= toversion):
                    selected_testcases.append(testcase['testcaseid'])

    return selected_testcases
                    
                
def parse_testenv_configfile(filename):
    """
    parse testenv.cfg file
    """
    GlobalObj.initTestenvObj()
    env = GlobalObj.getTestenvObj()
    cp = ConfigParser.SafeConfigParser(dict_type=OrderedDict)
    sections_to_functions_mapping = {
        "export" : "addExportdir",
        "server" : "addServer",
        "brick"  : "addBrick",
        "volume" : "addVolume",
        "client" : "addClient",
        "mountdevice" : "addMountDevice",
        "mount"  : "addMount",
        "defaults" : "addDefaults"}
    section_pattern = re.compile('(export|server|brick|volume|client|mountdevice|mount)*')
    if not cp.read(filename):
        print "Error reading file ' %s '.File  Not found " % filename
        return 1
    else:
        defaults = dict(cp.defaults())
        function = getattr(env, "addDefaults")
        function(**defaults)
        sections = cp.sections()
        for section in sections:
            items = dict(cp.items(section))
            matched_obj = section_pattern.match((section.lower()))
            result = matched_obj.group(0)
            if result is '':
                continue
            else:
                funcname = sections_to_functions_mapping[result]
                function = getattr(env, funcname)
                necessary_options = []
    
                if re.match('export', result):
                    necessary_options = ["dir"]
                    if verify_necessary_options(cp, section, necessary_options):
                        dir_ = items.pop('dir')
                        function(section, dir_, **items)                  
                    else:
                        return 1

                elif re.match('server', result):
                    necessary_options = ["hostname", "user", "password",
                                         "glusterversion"]
                    if verify_necessary_options(cp, section, necessary_options):
                        hostname = items.pop('hostname')
                        user = items.pop('user')
                        password = items.pop('password')
                        glusterversion = items.pop('glusterversion')
                        function(section, hostname, user, password,
                                 glusterversion, **items)
                    else:
                        return 1

                elif re.match('client', result):
                    necessary_options = ["hostname", "user", "password",
                                         "glusterversion"]
                    if verify_necessary_options(cp, section, necessary_options):
                        hostname = items.pop('hostname')
                        user = items.pop('user')
                        password = items.pop('password')
                        glusterversion = items.pop('glusterversion')
                        function(section, hostname, user, password,
                                 glusterversion, **items)
                    else:
                        return 1                    

                elif re.match('brick', result):
                    necessary_options = ["hostname", "path"]
                    if verify_necessary_options(cp, section, necessary_options):
                        hostname = items.pop('hostname')
                        path = items.pop('path')
                        function(section, hostname, path, **items)
                    else:
                        return 1

                elif re.match('volume', result):
                    necessary_options = ["volumename", "volumetype",
                                         "count", "transporttype",
                                         "bricks"]
                    if verify_necessary_options(cp, section, necessary_options):
                        volumename = items.pop('volumename')
                        volumetype = items.pop('volumetype')
                        count = items.pop('count')
                        transporttype = items.pop('transporttype')
                        bricks = items.pop('bricks')
                        function(section, volumename, volumetype,
                                 count, transporttype, bricks)
                    else:
                        return 1

                elif re.match('mountdevice', result):
                    necessary_options = ["hostname", "volumename"]
                    if verify_necessary_options(cp, section, necessary_options):
                        hostname = items.pop('hostname')
                        volumename = items.pop('volumename')
                        function(section, hostname, volumename)

                elif re.match('mount', result):
                    necessary_options = ["client", "dir", "device"]
                    if verify_necessary_options(cp, section, necessary_options):
                        client = items.pop('client')
                        dir_ = items.pop('dir')
                        device = items.pop('device')
                        function(section, client, dir_, device, **items)

                    else:
                        return 1
    return 0                                          
                    
            
__all__ = ['parse_testrun_info_file',
           'parse_testcaseslist_file',
           'parse_testenv_configfile']