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            time.sleep(interval)
81            print('running...')
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 main():
93    """
94    Script entry point
95    """
96    parser = argparse.ArgumentParser(
97        prog='pipeline-status',
98        description='check or wait on a pipeline status')
99
100    parser.add_argument('-t', '--timeout', type=int, default=7200,
101                        help=('Amount of time (in seconds) to wait for the '
102                              'pipeline to complete.  Defaults to '
103                              '%(default)s'))
104    parser.add_argument('-i', '--interval', type=int, default=60,
105                        help=('Amount of time (in seconds) to wait between '
106                              'checks of the pipeline status.  Defaults '
107                              'to %(default)s'))
108    parser.add_argument('-w', '--wait', action='store_true', default=False,
109                        help=('Wether to wait, instead of checking only once '
110                              'the status of a pipeline'))
111    parser.add_argument('-p', '--project-id', type=int, default=11167699,
112                        help=('The GitLab project ID. Defaults to the project '
113                              'for https://gitlab.com/qemu-project/qemu, that '
114                              'is, "%(default)s"'))
115    try:
116        default_commit = get_local_branch_commit()
117        commit_required = False
118    except ValueError:
119        default_commit = ''
120        commit_required = True
121    parser.add_argument('-c', '--commit', required=commit_required,
122                        default=default_commit,
123                        help=('Look for a pipeline associated with the given '
124                              'commit.  If one is not explicitly given, the '
125                              'commit associated with the local branch named '
126                              '"staging" is used.  Default: %(default)s'))
127    parser.add_argument('--verbose', action='store_true', default=False,
128                        help=('A minimal verbosity level that prints the '
129                              'overall result of the check/wait'))
130
131    args = parser.parse_args()
132
133    try:
134        if args.wait:
135            success = wait_on_pipeline_success(
136                args.timeout,
137                args.interval,
138                args.project_id,
139                args.commit)
140        else:
141            status = get_pipeline_status(args.project_id,
142                                         args.commit)
143            success = status['status'] == 'success'
144    except Exception as error:      # pylint: disable=W0703
145        success = False
146        if args.verbose:
147            print("ERROR: %s" % error.args[0])
148
149    if success:
150        if args.verbose:
151            print('success')
152        sys.exit(0)
153    else:
154        if args.verbose:
155            print('failure')
156        sys.exit(1)
157
158
159if __name__ == '__main__':
160    main()
161