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