1#!/usr/bin/env python3
2#
3# Copyright (c) 2019-2020 Red Hat, Inc.
4#
5# Author:
6#  Cleber Rosa <crosa@redhat.com>
7#
8# This work is licensed under the terms of the GNU GPL, version 2 or
9# later.  See the COPYING file in the top-level directory.
10
11"""
12Checks the GitLab pipeline status for a given commit ID
13"""
14
15# pylint: disable=C0103
16
17import argparse
18import http.client
19import json
20import os
21import subprocess
22import time
23import sys
24
25
26class CommunicationFailure(Exception):
27    """Failed to communicate to gitlab.com APIs."""
28
29
30class NoPipelineFound(Exception):
31    """Communication is successfull but pipeline is not found."""
32
33
34def get_local_branch_commit(branch='staging'):
35    """
36    Returns the commit sha1 for the *local* branch named "staging"
37    """
38    result = subprocess.run(['git', 'rev-parse', branch],
39                            stdin=subprocess.DEVNULL,
40                            stdout=subprocess.PIPE,
41                            stderr=subprocess.DEVNULL,
42                            cwd=os.path.dirname(__file__),
43                            universal_newlines=True).stdout.strip()
44    if result == branch:
45        raise ValueError("There's no local branch named '%s'" % branch)
46    if len(result) != 40:
47        raise ValueError("Branch '%s' HEAD doesn't look like a sha1" % branch)
48    return result
49
50
51def get_pipeline_status(project_id, commit_sha1):
52    """
53    Returns the JSON content of the pipeline status API response
54    """
55    url = '/api/v4/projects/{}/pipelines?sha={}'.format(project_id,
56                                                        commit_sha1)
57    connection = http.client.HTTPSConnection('gitlab.com')
58    connection.request('GET', url=url)
59    response = connection.getresponse()
60    if response.code != http.HTTPStatus.OK:
61        raise CommunicationFailure("Failed to receive a successful response")
62    json_response = json.loads(response.read())
63
64    # As far as I can tell, there should be only one pipeline for the same
65    # project + commit. If this assumption is false, we can add further
66    # filters to the url, such as username, and order_by.
67    if not json_response:
68        raise NoPipelineFound("No pipeline found")
69    return json_response[0]
70
71
72def wait_on_pipeline_success(timeout, interval,
73                             project_id, commit_sha):
74    """
75    Waits for the pipeline to finish within the given timeout
76    """
77    start = time.time()
78    while True:
79        if time.time() >= (start + timeout):
80            msg = ("Timeout (-t/--timeout) of %i seconds reached, "
81                   "won't wait any longer for the pipeline to complete")
82            msg %= timeout
83            print(msg)
84            return False
85
86        status = get_pipeline_status(project_id, commit_sha)
87        if status['status'] == 'running':
88            print('running...')
89            time.sleep(interval)
90            continue
91
92        if status['status'] == 'success':
93            return True
94
95        msg = "Pipeline failed, check: %s" % status['web_url']
96        print(msg)
97        return False
98
99
100def create_parser():
101    parser = argparse.ArgumentParser(
102        prog='pipeline-status',
103        description='check or wait on a pipeline status')
104
105    parser.add_argument('-t', '--timeout', type=int, default=7200,
106                        help=('Amount of time (in seconds) to wait for the '
107                              'pipeline to complete.  Defaults to '
108                              '%(default)s'))
109    parser.add_argument('-i', '--interval', type=int, default=60,
110                        help=('Amount of time (in seconds) to wait between '
111                              'checks of the pipeline status.  Defaults '
112                              'to %(default)s'))
113    parser.add_argument('-w', '--wait', action='store_true', default=False,
114                        help=('Wether to wait, instead of checking only once '
115                              'the status of a pipeline'))
116    parser.add_argument('-p', '--project-id', type=int, default=11167699,
117                        help=('The GitLab project ID. Defaults to the project '
118                              'for https://gitlab.com/qemu-project/qemu, that '
119                              'is, "%(default)s"'))
120    try:
121        default_commit = get_local_branch_commit()
122        commit_required = False
123    except ValueError:
124        default_commit = ''
125        commit_required = True
126    parser.add_argument('-c', '--commit', required=commit_required,
127                        default=default_commit,
128                        help=('Look for a pipeline associated with the given '
129                              'commit.  If one is not explicitly given, the '
130                              'commit associated with the local branch named '
131                              '"staging" is used.  Default: %(default)s'))
132    parser.add_argument('--verbose', action='store_true', default=False,
133                        help=('A minimal verbosity level that prints the '
134                              'overall result of the check/wait'))
135    return parser
136
137def main():
138    """
139    Script entry point
140    """
141    parser = create_parser()
142    args = parser.parse_args()
143    success = False
144    try:
145        if args.wait:
146            success = wait_on_pipeline_success(
147                args.timeout,
148                args.interval,
149                args.project_id,
150                args.commit)
151        else:
152            status = get_pipeline_status(args.project_id,
153                                         args.commit)
154            success = status['status'] == 'success'
155    except Exception as error:      # pylint: disable=W0703
156        if args.verbose:
157            print("ERROR: %s" % error.args[0])
158    except KeyboardInterrupt:
159        if args.verbose:
160            print("Exiting on user's request")
161
162    if success:
163        if args.verbose:
164            print('success')
165        sys.exit(0)
166    else:
167        if args.verbose:
168            print('failure')
169        sys.exit(1)
170
171
172if __name__ == '__main__':
173    main()
174