~allanlesage/uci-engine/coverage-extractor

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
#!/usr/bin/env python
"""
Reports global status for a stack
"""
#
# Copyright (C) 2012, Canonical Ltd (http://www.canonical.com/)
#
# This file is part of cupstream2distro.
#
# 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, version 3 of
# the License.
#
# 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, see
# <http://www.gnu.org/licenses/>.
#

import logging
import argparse
import os
import xml.etree.ElementTree as etree
import sys

JENKINS_ROOT_DEFAULT = '/iSCSI/jenkins'

class CU2DStackStatus(object):
    ''' This class search the latest results and each step and report the global
    result of the master job
    '''

    def __init__(self):
        ''' Constructor '''
        self.args = self.__parse_args()

        self.stack = self.args.stack
        self.release = self.args.release

        self.jenkinsdir = self.args.jenkins_root
        self.jobs = ('1.0prepare', '2.1build', '2.2check', '3.0publish')
        self.statuses = ('NA', 'SUCCESS', 'UNSTABLE', 'ABORTED', 'FAILURE')
        self.jobformat = 'cu2d-{}-{}-{}'
        self.jobsdir = os.path.join(self.jenkinsdir, 'jobs')
        self.stack_status = -1

        self.outputfile = os.path.join(self.jenkinsdir, 'cu2d', 'work',
                                       self.release, self.stack,
                                       'stack.status')
        print (self.outputfile)

    def __parse_args(self):
        ''' Argument parser '''
        parser = argparse.ArgumentParser(description='Start a jenkins slave')
        parser.add_argument('-d', '--debug', action='store_true',
                            default=False, help='enable debug mode')
        parser.add_argument('-s', '--stack',
                            help='name of the stack')
        parser.add_argument('-r', '--release',
                            help='name of the release (default: head)')
        parser.add_argument('-j', '--jenkins-root',
                            default=JENKINS_ROOT_DEFAULT,
                            help='jenkins root directory (default: {}'.format(
                                JENKINS_ROOT_DEFAULT))
        args = parser.parse_args()
        set_logging(args.debug)
        logging.debug(args)
        if not args.stack or not args.release:
            logging.error('Stack and release parameters are mandatory')
            sys.exit(1)
        return args

    def get_stack_status(self):
        ''' Walk down the result tree to find the status for the stack
        0: Pass
        1: Failed
        2: Unstable
        '''
        overall = 0
        for job in self.jobs:
            jobdir = self.jobformat.format(self.stack, self.release, job)
            jobpath = os.path.join(self.jobsdir, jobdir)

            buildnumber = 0
            nextbuildpath = os.path.join(jobpath, 'nextBuildNumber')
            try:
                with open(nextbuildpath, 'r') as fnb:
                    nextnum = fnb.read()
                buildnumber = int(nextnum) - 1
            except IOError:
                logging.warning('error reading %s, ignoring!', nextbuildpath)
                continue
            logging.debug('%s : %s', jobpath, buildnumber)

            buildxml = os.path.join(jobpath, 'builds', str(buildnumber),
                                    'build.xml')
            if not os.path.isfile(buildxml):
                logging.warning('file does not exist %s, ignoring!', buildxml)
                continue

            result = test_result(buildxml)
            logging.debug('Step %s : %s', job, result)

            overall = max(overall, self.statuses.index(result))
        self.stack_status = self.statuses[overall]
        return self.stack_status

    def write_status(self):
        ''' Write result to file stack_status '''
        o_status = {'NA': '-1',
                    'SUCCESS': '0',
                    'UNSTABLE': '2',
                    'ABORTED': '3',
                    'FAILURE': '1'}
        if not os.path.isdir(os.path.dirname(self.outputfile)):
            logging.error('Output directory does not exist: %s, exiting!',
                          os.path.dirname(self.outputfile))
            sys.exit(1)

        with open(self.outputfile, 'w') as fout:
            fout.write(o_status[self.stack_status])


def test_result(path):
    '''Returns a build result'''

    tree = etree.parse(path)
    root = tree.getroot()
    result = root.find('result')
    return result.text


def set_logging(debugmode=False):
    """Initialize logging"""
    logging.basicConfig(
        level=logging.DEBUG if debugmode else logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s")
    logging.debug('Debug mode enabled')

if __name__ == '__main__':
    cu2d = CU2DStackStatus()
    status = cu2d.get_stack_status()
    cu2d.write_status()